forked from therohit777/Hacktober_algo_bucket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
All Tree travesal in single one
94 lines (78 loc) · 1.78 KB
/
All Tree travesal in single one
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
#include <bits/stdc++.h>
using namespace std;
//Code by Abhimanyu
struct node {
int data;
struct node * left, * right;
};
void allTraversal(node * root, vector < int > & pre, vector < int > & in , vector < int > & post) {
stack < pair < node * , int >> st;
st.push({
root,
1
});
if (root == NULL) return;
while (!st.empty()) {
auto it = st.top();
st.pop();
if (it.second == 1) {
pre.push_back(it.first -> data);
it.second++;
st.push(it);
if (it.first -> left != NULL) {
st.push({
it.first -> left,
1
});
}
}
else if (it.second == 2) {
in .push_back(it.first -> data);
it.second++;
st.push(it);
if (it.first -> right != NULL) {
st.push({
it.first -> right,
1
});
}
}
else {
post.push_back(it.first -> data);
}
}
}
struct node * newNode(int data) {
struct node * node = (struct node * ) malloc(sizeof(struct node));
node -> data = data;
node -> left = NULL;
node -> right = NULL;
return (node);
}
int main() {
struct node * root = newNode(1);
root -> left = newNode(2);
root -> left -> left = newNode(4);
root -> left -> right = newNode(5);
root -> right = newNode(3);
root -> right -> left = newNode(6);
root -> right -> right = newNode(7);
vector < int > pre, in , post;
allTraversal(root, pre, in , post);
cout << "The preorder Traversal is : ";
for (auto nodeVal: pre) {
cout << nodeVal << " ";
}
cout << endl;
cout << "The inorder Traversal is : ";
for (auto nodeVal: in ) {
cout << nodeVal << " ";
}
cout << endl;
cout << "The postorder Traversal is : ";
for (auto nodeVal: post) {
cout << nodeVal << " ";
}
cout << endl;
return 0;
}