-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathBinary_Tree_Vertical_Order_Traversal.cpp
More file actions
37 lines (37 loc) · 1.03 KB
/
Binary_Tree_Vertical_Order_Traversal.cpp
File metadata and controls
37 lines (37 loc) · 1.03 KB
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
map <int, vector<int>> verticalMap;
vector<vector<int>> result;
if(!root) {
return result;
}
queue < pair<TreeNode*, int> > Q;
Q.push(make_pair(root, 0));
while(!Q.empty()) {
TreeNode* node = Q.front().first;
int indx = Q.front().second;
Q.pop();
verticalMap[indx].push_back(node->val);
if(node->left) {
Q.push(make_pair(node->left, indx - 1));
}
if(node->right) {
Q.push(make_pair(node->right, indx + 1));
}
}
for(auto it = verticalMap.begin(); it != verticalMap.end(); ++it) {
result.push_back(it->second);
}
return result;
}
};