Vertical Order Traversal of a Binary Tree
Given a binary tree, return the vertical order traversal of its nodes values.
For each node at position (X, Y)
, its left and right children respectively will be at positions (X-1, Y-1)
and (X+1, Y-1)
.
Running a vertical line from X = -infinity
to X = +infinity
, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y
coordinates).
If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.
Return an list of non-empty reports in order of X
coordinate. Every report will have a list of values of nodes.
/**
* 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:
vector<vector<int>> verticalTraversal(TreeNode* root) {
if(root==NULL)
{
return {};
}
map<int,vector<int>>m;
vector<vector<int>>v;
queue<pair<TreeNode*,int>>q;
q.push({root,1});
while(!q.empty())
{
int k=q.size();
map<int,set<int>>m1;
while(k--)
{
TreeNode*curr=q.front().first;
int hd=q.front().second;
q.pop();
m1[hd].insert(curr->val);
if(curr->left)
{
q.push({curr->left,hd-1});
}
if(curr->right)
{
q.push({curr->right,hd+1});
}
}
for(auto x:m1)
{
for(auto d:x.second)
{
m[x.first].push_back(d);
}
}
}
for(auto x:m)
{
v.push_back(x.second);
}
return v;
}
};