-
Notifications
You must be signed in to change notification settings - Fork 1
/
9_5_Inorder_Tree_traversal
113 lines (100 loc) · 2.15 KB
/
9_5_Inorder_Tree_traversal
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
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
template <typename T>
class node {
public:
T data;
node *left, *right, *parent;
node() {
left = right = parent = NULL;
}
};
template <typename T>
class BinaryTree {
public:
node<T> *root;
BinaryTree() {
root = NULL;
}
void _insert(T a, node<T> *n) {
if (root) {
if (a < n->data) {
if (n->left)
_insert(a, n->left);
else {
node<T> *leaf = new node<T>();
leaf->data = a;
leaf->parent = n;
n->left = leaf;
}
}
else {
if (n->right)
_insert(a, n->right);
else {
node<T> *leaf = new node<T>();
leaf->data = a;
leaf->parent = n;
n->right = leaf;
}
}
}
else {
node<T> *leaf = new node<T>();
leaf->data = a;
root = leaf;
}
}
void insert(T a) {
_insert(a, root);
}
};
template <typename T>
void printInOrder(node<T>* n) {
node<T> *curr = n;
int goRight = 0;
while (curr) {
if (curr->left && goRight == 0) {
curr = curr->left;
}
else {
goRight = 0;
cout << curr->data << endl;
if (curr->right) {
curr = curr->right;
}
else if (curr->parent) {
goRight = 1;
if ((curr->parent->left) && (curr->parent->left == curr)) {
curr = curr->parent;
}
else if (curr->parent->parent) {
node<T>* grandParent = curr->parent->parent;
if ((grandParent->right) && (grandParent->right->right) && (grandParent->right->right == curr)) {
break;
}
curr = grandParent;
}
else
break;
}
else
break;
}
}
}
int main() {
vector<int> v = { 10, 5, 15, 3, 12, 1, 4, 2, 11, 7 };
BinaryTree<int> B;
for (int i = 0; i < v.size(); i++) {
B.insert(v[i]);
}
printInOrder<int>(B.root);
return 0;
}