-
Notifications
You must be signed in to change notification settings - Fork 2
/
iterative_inorder.cpp
83 lines (64 loc) · 1.46 KB
/
iterative_inorder.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
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
class Tree {
public:
int data;
Tree *left, *right;
Tree(int data) {
this->data = data;
this->left = this->right = NULL;
}
};
// Tree *root = NULL;
Tree* make_Tree(Tree *root, int data) {
if(root == NULL) {
root = new Tree(data);
return root;
}
queue<Tree*> q_tree;
q_tree.push(root);
while(!q_tree.empty()) {
Tree *temp = q_tree.front();
q_tree.pop();
if(!temp->left) {
temp->left = new Tree(data);
break;
}
else if(!temp->right) {
temp->right = new Tree(data);
break;
}
else {
q_tree.push(temp->left);
q_tree.push(temp->right);
}
}
return root;
}
void inorder(Tree *root) {
if(root == NULL) return;
stack<Tree*> stk_tree;
// stk_tree.push(root);
Tree *temp = root;
while(!stk_tree.empty() || temp != NULL) {
while(temp!= NULL) {
stk_tree.push(temp);
temp = temp->left;
}
temp = stk_tree.top();
cout << temp->data << " ";
stk_tree.pop();
temp = temp->right;
}
cout << endl;
}
int main() {
Tree* root = NULL;
int data[] = {1,2,3,4,5,6,7,8,9};
for(int i = 0; i < 9; i++) root = make_Tree(root, data[i]);
cout << "In Order : ";
inorder(root);
return 0;
}