[LeetCode314]Binary Tree Vertical Order Traversal

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Examples:
Given binary tree [3,9,20,null,null,15,7],
        3
       / \
      9  20
      /   \
     15   7
return its vertical order traversal as:
    [
      [9],
      [3,15],
      [20],
      [7]
    ]
Given binary tree [3,9,20,4,5,2,7],
    _3_
   /   \
  9    20
 / \   / \
4   5 2   7
return its vertical order traversal as:
    [
      [4],
      [9],
      [3,5,2],
      [20],
      [7]
    ]
Hide Company Tags Facebook
Hide Tags Hash Table
Hide Similar Problems (E) Binary Tree Level Order Traversal

这题一眼就可以看出: 对于current root, 它和 root->left->right and root->left->right 在一个vector 里。我看出这个以后就再也看不出别的了(苦笑。。

看了别人的实现方法,很好玩~BFS + hashmap。
如果current root 的index 是idx: let the index of left node be idx-1 and index of right node be idx+1 then the index of root->left->right is also idx!!!(same with root->right->left)

/**
 * 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>> mp;
        queue<pair<int, TreeNode*>> q;
        vector<vector<int>> res;
        if(!root) return res;
        q.push(make_pair(0,root));
        while(!q.empty()){
            int sz = q.size();
            for(int i = 0; i<sz; ++i){
                TreeNode* cur = q.front().second;
                int idx = q.front().first;
                q.pop();
                mp[idx].push_back(cur->val);
                if(cur->left) q.push(make_pair(idx-1, cur->left));
                if(cur->right) q.push(make_pair(idx+1,cur->right));
            }
        }
        for(auto m : mp){
            res.push_back(m.second);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值