[leetcode] 314. Binary Tree Vertical Order Traversal 解题报告

题目链接:https://leetcode.com/problems/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]
]

思路:和水平遍历二叉树类似,我们使用队列层次遍历二叉树,并为每个结点附加一个列信息.然后使用一个map来存储以列号为关键字的结点值.最后我们遍历完所有结点之后就会将每一列存储到map的一个列号为关键字的集合中去,然后将其复制到我们要返回的数组中去即可.

代码如下:

/**
 * 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) {
        if(!root) return result;
        queue<pair<TreeNode*, int>> que;
        que.push(make_pair(root, 1));
        while(!que.empty())
        {
            auto node = que.front();
            que.pop();
            hash[node.second].push_back(node.first->val);
            auto left = node.first->left, right = node.first->right;
            if(left) que.push(make_pair(left, node.second-1));
            if(right) que.push(make_pair(right, node.second+1));
        }
        for(auto val: hash) result.push_back(val.second);
        return result;
    }
private:
    map<int, vector<int>> hash;
    vector<vector<int>> result;
};
参考:https://leetcode.com/discuss/88008/simple-c-solution-8ms


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值