[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
- [leetcode] 314. Binary Tree Vertical Order Traversal 解题报告
- [Leetcode] 314. Binary Tree Vertical Order Traversal 解题报告
- LeetCode 314. Binary Tree Vertical Order Traversal
- Leetcode 314. Binary Tree Vertical Order Traversal
- LeetCode 314. Binary Tree Vertical Order Traversal
- Leetcode Binary Tree Vertical Order Traversal
- [Leetcode]Binary Tree Vertical Order Traversal
- LeetCode. 314 Binary Tree Vertical Order Traversal
- [LeetCode]Binary Tree Level Order Traversal II,解题报告
- LeetCode-Binary Tree Level Order Traversal-解题报告
- 【LeetCode】Binary Tree Level Order Traversal 解题报告
- 【LeetCode】Binary Tree Level Order Traversal II 解题报告
- 【LeetCode】 Binary Tree Zigzag Level Order Traversal 解题报告
- LeetCode(102) Binary Tree Level Order Traversal解题报告
- LeetCode(103) Binary Tree Zigzag Level Order Traversal解题报告
- LeetCode(107) Binary Tree Level Order Traversal II解题报告
- [leetcode] 102. Binary Tree Level Order Traversal 解题报告
- [leetcode] 107. Binary Tree Level Order Traversal II 解题报告
- vs错误提示:调运的目标异常,此实现不是 Windows 平台 FIPS 验证的加密算法的一部分
- 九度题目1431:Sort
- 51nod 1055最长等差数列 dp
- Android系统Bluetooh移植简要说明
- http中get与post的真正区别
- [leetcode] 314. Binary Tree Vertical Order Traversal 解题报告
- 微信开发配置文件详细注释版
- Linux sudo 命令详解
- Android的IPC机制(五)—— ContentProvider的使用
- C++中string类的实现
- hdu 2033 人见人爱A+B
- iOS-KVO
- Nginx + IIS + Web前端(Spring MVC)——负载均衡(二)
- Linux 常用命令1——ls