-
Notifications
You must be signed in to change notification settings - Fork 43
/
Pre_Post_Inorder_traversal_in_a_single_flow.cpp
114 lines (98 loc) · 2.23 KB
/
Pre_Post_Inorder_traversal_in_a_single_flow.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
105
106
107
108
109
110
111
112
113
114
#include <iostream>
#include <vector>
#include <stack>
#include <utility>
using namespace std;
#define null NULL
struct Node
{
int data;
struct Node *left;
struct Node *right;
Node(int val)
{
data = val;
left = right = null;
}
};
class io
{
public:
vector<int> takeVectorInput(vector<int> vec, int vectorSize)
{
for (int index = 0; index < vectorSize; index++)
{
int num;
cin >> num;
vec.push_back(num);
}
return vec;
}
void printVector(vector<int> vec)
{
for (auto index = vec.begin(); index != vec.end(); index++)
cout << *index << " ";
cout << endl;
}
};
class Solution
{
public:
void preInPostTraversal(Node *root)
{
stack<pair<Node *, int>> st;
st.push({root, 1});
vector<int> pre, post, in;
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);
}
io obIo;
cout << "Preorder: ";
obIo.printVector(pre);
cout << "Postorder: ";
obIo.printVector(post);
cout << "Inorder: ";
obIo.printVector(in);
}
};
int main()
{
struct Node *root = new Node(1);
// left
root->left = new Node(2);
root->left->left = new Node(3);
root->left->right = new Node(4);
// right
root->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
Solution obSol;
obSol.preInPostTraversal(root);
/*
The Tree will look like
1
2 5
3 4 6 7
*/
return 0;
}