-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathVertical Order Traversal of a Binary Tree.cpp
85 lines (65 loc) · 2.5 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
/*
Solution by Rahul Surana
***********************************************************
Given the root of a binary tree, calculate the vertical order traversal of the binary tree.
For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1)
and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).
The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting
from the leftmost column and ending on the rightmost column.
There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.
Return the vertical order traversal of the binary tree.
***********************************************************
*/
#include <bits/stdc++.h>
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
map<int,vector<pair<int,int>>> m;
void t(TreeNode* root, int i){
queue<pair<TreeNode*,int>> q;
q.push({root,0});
int l = 0;
while(!q.empty()){
int s = q.size();
while(s--) {
TreeNode* cur = q.front().first;
int x = q.front().second;
q.pop();
if(cur == NULL) continue;
cout << x <<" "<<cur->val<<" ";
if(m.find(x) == m.end()) m[x] = vector<pair<int,int>>();
m[x].push_back({l,cur->val});
q.push({cur->left,x-1});
q.push({cur->right,x+1});
}
l++;
}
cout<<"\n";
}
vector<vector<int>> verticalTraversal(TreeNode* root) {
t(root, 0);
// sort(m.begin(),m.end());
vector<vector<int>> ans(m.size(),vector<int>());
int i = 0;
for(auto x: m){
sort(x.second.begin(),x.second.end());
// sort(a.begin(),a.end());
for(auto x1: x.second){
ans[i].push_back(x1.second);
}
i++;
// sort(ans[ans.size()-1].begin(),ans[ans.size()-1].end());
}
return ans;
}
};