-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhill_climbing_search.cpp
131 lines (108 loc) · 2.13 KB
/
hill_climbing_search.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/*
Author: Quan
Description: hill climbing search with tree & stack
*/
#include <stdio.h>
#include <stdlib.h>
struct Tree{
int value;
struct Tree *left;
struct Tree *right;
};
struct Node{
Tree *Data;
Node *Next;
};
struct Stack{
Node *Top;
};
Tree *MakeTree(int value){
Tree *p = (Tree*)malloc(sizeof(Tree));
p->value= value;
p->left = NULL;
p->right = NULL;
return p;
}
void Init(Stack &S){
S.Top = NULL;
}
Node *MakeNode(Tree *data){
Node *p = (Node*)malloc(sizeof(Node));
p->Next = NULL;
p->Data = data;
return p;
}
void Push(Stack &S, Tree *item){
Node *p = MakeNode(item);
p->Next = S.Top;
S.Top = p;
}
Tree *Pop(Stack &S){
Tree *x = S.Top->Data;
S.Top = S.Top->Next;
return x;
}
//Them va sap xep phan tu vao L
void PushL(Stack &S, Tree *T){
if(T->left!=NULL && T->right!=NULL){
if(T->left->value>T->right->value){
Push(S, T->left);
Push(S, T->right);
}
else{
Push(S, T->right);
Push(S, T->left);
}
}else{
if(T->left!=NULL){
Push(S, T->left);
}
if(T->right!=NULL){
Push(S, T->right);
}
}
}
// Tim kiem leo doi
struct Tree *hill_climbing_search(Stack &S, int value){
// dung neu khong tim thay
if(S.Top==NULL){
return NULL;
}
// Lay phan tu dau tien trong danh sach L
struct Tree *x = Pop(S);
printf("%d\t", x->value);
// tra ve tree neu tim thay
if(x->value==value){
return x;
}
// Them phan tu vao L neu chua tim thay
PushL(S, x);
// tiep tuc tim kiem
return hill_climbing_search(S, value);
}
int main(){
struct Stack L;
// Khoi tao du lieu
struct Tree *T = MakeTree(12);
T->left = MakeTree(1);
T->right = MakeTree(2);
T->left->left = MakeTree(3);
T->left->right = MakeTree(2);
T->left->right->left = MakeTree(0);
T->left->right->right = MakeTree(6);
T->right->right = MakeTree(3);
T->right->right->right = MakeTree(0);
// Them phan tu dau tien vao L
Push(L, T);
printf("Qua trinh tim kiem\n");
Tree *search = hill_climbing_search(L, 0);
printf("\nKet Thuc qua trinh tim kiem\n");
// PushMin(S, T);
// if(search!=NULL){
printf("%d\t", search->value);
// }
//
// printf("%d\t", Pop(S)->value);
// printf("%d", Pop(S)->value);
return 0;
}