-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVerticalOrderTraversalBinaryTree.cpp
63 lines (49 loc) · 1.19 KB
/
VerticalOrderTraversalBinaryTree.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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include<bits/stdc++.h>
using namespace std ;
vector<vector<int> > Solution::verticalOrderTraversal(TreeNode* root) {
map<int,vector<int>>mapp;
queue<pair<int, TreeNode* >>q;
if(root==NULL)
{
vector<vector<int>> ans;
return ans;
}
q.push(make_pair(0,root)) ;
int mind=INT_MAX;
int maxd=INT_MIN;
while(!q.empty())
{
int d=q.front().first ;
TreeNode *temp=q.front().second;
q.pop() ;
mind=min(mind,d) ;
maxd=max(maxd,d) ;
mapp[d].push_back(temp->val) ;
if(temp->left)
{q.push(make_pair(d-1,temp->left)) ;
}
if(temp->right)
{q.push(make_pair(d+1,temp->right)) ;
}
}
vector<vector<int>>ans;
for(int i=mind;i<=maxd;i++)
{
vector<int>temp;
for(int j=0;j<mapp[i].size();j++)
{
temp.push_back(mapp[i][j]);
}
ans.push_back(temp) ;
}
return ans;
}