-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfs.cpp
132 lines (114 loc) · 2.39 KB
/
dfs.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
132
#include <iostream>
using namespace std;
#define MAX 6 //Max of nodes & stack
struct Tree {
int data;
Tree* left;
Tree* right;
};
struct Stack{
Tree* data[MAX];
int top;
};
Tree *leaf, *newNode, *root = NULL;
Stack stack;
bool isFull(){
return (stack.top == MAX) ? true : false;
}
void push(Tree *value){
if(!isFull()){
stack.top++;
stack.data[stack.top] = value;
}
else{
cout << "stack penuh!";
}
}
void initStack(){
stack.top = -1;
}
bool isEmpty(){
return (stack.top == -1) ? true : false;
}
void pop(){
if(isEmpty()){
cout << "stack masih kosong!\n";
return ;
}
//stack.data[stack.top] = NULL;
stack.top--;
}
void printStack(){
if(isEmpty()){
cout << "stack masih kosong!";
return;
}
for(int i = 0 ; i <= stack.top;i++){
// cout << stack.data[i] << " ";
}
cout << "\n";
}
void addLeft(Tree* current, int data) {
if (current->left != NULL) {
cout << "Kiri tidak kosong!\n";
return;
}
newNode = new Tree();
newNode->left = NULL;
newNode->right = NULL;
newNode->data = data;
current->left = newNode;
}
void addRight(Tree* current, int data) {
if (current->right != NULL) {
cout << "Kanan tidak kosong!\n";
return;
}
newNode = new Tree();
newNode->left = NULL;
newNode->right = NULL;
newNode->data = data;
current->right = newNode;
}
Tree* createTree(int data) {
newNode = new Tree();
newNode->left = NULL;
newNode->right = NULL;
newNode->data = data;
return newNode;
}
void dfs(Tree *current){
//Inisialisasi stack
initStack();
//Masukan kedalam stack
push(current);
//Jika tidak kosong pop
while (!isEmpty()) {
Tree *node = stack.data[stack.top];
pop();
//Print data dari node
cout << node->data << " ";
//Jika kanan tidak kosong
if (node->right != NULL) {
//push
push(node->right);
}
//jika kiri tidak kosong
if (node->left != NULL) {
//pushh
push(node->left);
}
}
}
int main(){
initStack();
leaf = createTree(0);
addLeft(leaf, 1);
addLeft(leaf->left, 4);
addRight(leaf, 2);
addRight(leaf->right, 3);
addLeft(leaf->right, 5);
addLeft(leaf->right->left, 6);
dfs(leaf);
return 0;
}