-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.cpp
105 lines (88 loc) · 2.09 KB
/
tree.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
#include <iostream>
using namespace std;
// node
struct Tree {
int data;
Tree* left;
Tree* right;
};
Tree* leaf, * leaf2, * leaf3, *nodeBaru, * root = NULL;
void preOrder(Tree* current) {
if (current != NULL) {
cout << " " << current->data;
preOrder(current->left);
preOrder(current->right);
}
}
void inOrder(Tree* current) {
if (current != NULL) {
inOrder(current->left);
cout << " " << current->data;
inOrder(current->right);
}
}
void postOrder(Tree* current) {
if (current != NULL) {
postOrder(current->left);
postOrder(current->right);
cout << " " << current->data;
}
}
void addRight(Tree* current, int data) {
if (current->right != NULL) {
cout << "Sisi kanan sudah ada\n";
}
else {
nodeBaru = new Tree();
nodeBaru->data = data;
nodeBaru->left = NULL;
nodeBaru->right = NULL;
current->right = nodeBaru;
}
}
void addLeft(Tree* current, int data) {
if (current->left != NULL) {
cout << "Sisi kiri sudah ada\n";
}
else {
nodeBaru = new Tree();
nodeBaru->data = data;
nodeBaru->left = NULL;
nodeBaru->right = NULL;
current->left = nodeBaru;
}
}
Tree* createTree(int data) {
nodeBaru = new Tree();
nodeBaru->data = data;
nodeBaru->left = NULL;
nodeBaru->right = NULL;
return nodeBaru;
}
void print(Tree *current){
cout << "PreOrder : ";
preOrder(current);
cout << "\n";
cout << "InOrder : ";
inOrder(current);
cout << "\n";
cout << "PostOrder : ";
postOrder(current);
}
int main() {
leaf = createTree(7);
addLeft(leaf,1);
addRight(leaf,9);
//left Side
addLeft(leaf->left,0);
addRight(leaf->left,3);
addRight(leaf->left->right,5);
addLeft(leaf->left->right,2);
addRight(leaf->left->right->right,6);
addLeft(leaf->left->right->left,4);
//right side
addRight(leaf->right,10);
addLeft(leaf->right,8);
print(leaf);
return 0;
}