forked from krishna14kant/Data-Structures-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVerticalOrderTraversalOfBinaryTree.cpp
More file actions
54 lines (54 loc) · 1.39 KB
/
VerticalOrderTraversalOfBinaryTree.cpp
File metadata and controls
54 lines (54 loc) · 1.39 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <set>
using namespace std;
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:
vector<vector<int>> verticalTraversal(TreeNode* root)
{
vector<vector<int>> ans;
queue<pair<TreeNode* , pair<int,int>>> q;
map<int , map<int , multiset<int>>> nodes;
q.push({root,{0,0}});
while(!q.empty())
{
auto p = q.front();
q.pop();
TreeNode* node = p.first;
int x = p.second.first;
int y = p.second.second;
nodes[x][y].insert(node->val);
if(node->left)
{
q.push({node->left,{x-1,y+1}});
}
if(node->right)
{
q.push({node->right,{x+1,y+1}});
}
}
for(auto p: nodes)
{
vector<int> set;
for(auto q: p.second)
{
for (auto k: q.second)
{
set.push_back(k);
}
}
ans.push_back(set);
}
return ans;
}
};