-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeBst.cpp
More file actions
98 lines (81 loc) · 1.7 KB
/
TreeBst.cpp
File metadata and controls
98 lines (81 loc) · 1.7 KB
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
#include <iostream>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
// Global pointers (same as your C code)
Node *root = nullptr, *temp, *ttemp, *p;
void init() {
root = nullptr;
}
void create_root(int x) {
root = new Node;
root->data = x;
root->left = root->right = nullptr;
}
void add_nodes(int x) {
temp = root;
while (temp != nullptr) {
ttemp = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
p = new Node;
p->data = x;
p->left = p->right = nullptr;
if (x < ttemp->data)
ttemp->left = p;
else
ttemp->right = p;
}
void inorder(Node *p) {
if (p != nullptr) {
inorder(p->left);
cout << "\t" << p->data;
inorder(p->right);
}
}
void preorder(Node *p) {
if (p != nullptr) {
cout << "\t" << p->data;
preorder(p->left);
preorder(p->right);
}
}
void postorder(Node *p) {
if (p != nullptr) {
postorder(p->left);
postorder(p->right);
cout << "\t" << p->data;
}
}
int main() {
init();
create_root(50);
add_nodes(30);
add_nodes(70);
add_nodes(90);
add_nodes(20);
add_nodes(10);
add_nodes(100);
add_nodes(60);
add_nodes(80);
add_nodes(55);
add_nodes(85);
add_nodes(25);
add_nodes(15);
add_nodes(35);
add_nodes(45);
add_nodes(59);
add_nodes(24);
cout << "\nInorder\n";
inorder(root);
cout << "\n\nPreorder\n";
preorder(root);
cout << "\n\nPostorder\n";
postorder(root);
return 0;
}