-
Notifications
You must be signed in to change notification settings - Fork 0
/
AllTreeTraversals.cpp
42 lines (39 loc) · 1.08 KB
/
AllTreeTraversals.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
//All Tree Traversals : In Pre Post order in on go using one stack
class Solution {
public:
vector<int>preInPostTraversal(TreeNode* root){
stack<pair<TreeNode*,int>> st;
st.push(root,1);
vector<int> pre,in,post;
if(root ==NULL)return;
while(!st.empty())
{
auto it = st.top();
st.pop();
if(it.second ==1)
{
pre.push_back(it.first->val);
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->val);
it.second++;
st.push(it);
if(it.first->right!=NULL)
{
st.push({it.first->right,1});
}
}
else
{
post.push_back(it.first->val);
}
}
}
};