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

来源:互联网 发布:ARPU数据展示模版 编辑:程序博客网 时间:2024/06/09 17:52

题目链接: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
原创粉丝点击