-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathVertical Order Traversal of a Binary Tree.cpp
95 lines (86 loc) · 2.11 KB
/
Vertical Order Traversal of a Binary Tree.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
#include<bits/stdc++.h>
#define ll int
using namespace std;
// ***********************************************************
// Following is the TreeNode class structure:
template <typename T>
class TreeNode {
public:
T val;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T val) {
this->val = val;
left = NULL;
right = NULL;
}
};
// ***********************************************************
TreeNode<ll>* createTree()
{
queue<TreeNode<ll>*> q;
TreeNode<ll> *root = nullptr;
ll val;
cout<<"Enter value of root - "<<endl;
cin>>val;
root = new TreeNode<ll>(val);
q.push(root);
while(q.size())
{
auto cur = q.front();
q.pop();
ll lef,rig;
cout<<"Enter left child of "<<cur->val<<endl;
cin>>lef;
cout<<"Enter right child of "<<cur->val<<endl;
cin>>rig;
if(lef==-1)
cur->left = nullptr;
else
{
TreeNode<ll> *l = new TreeNode<ll>(lef);
cur->left = l;
q.push(l);
}
if(rig==-1)
cur->right = nullptr;
else
{
TreeNode<ll> *r = new TreeNode<ll>(rig);
cur->right = r;
q.push(r);
}
}
return root;
}
vector<int> verticalOrderTraversal(TreeNode<int> *root)
{
map<ll,map<ll,vector<ll>>> m;
queue<pair<TreeNode<ll>*,pair<ll,ll>>> q;
q.push({root,{0,0}});
while(q.size())
{
auto p = q.front();
ll c = p.second.first;
ll r = p.second.second;
TreeNode<ll>* cur = p.first;
q.pop();
m[c][r].push_back(cur->val);
if(cur->left)
q.push({cur->left,{c-1,r+1}});
if(cur->right)
q.push({cur->right,{c+1,r+1}});
}
vector<ll> ans;
for(auto i:m)
for(auto j:i.second)
ans.insert(ans.end(),j.second.begin(),j.second.end());
return ans;
}
int main()
{
TreeNode<ll> *root = createTree();
vector<ll> ans = verticalOrderTraversal(root);
for(auto i:ans)
cout<<i<<" ";
}