Leetcode Binary Tree Vertical Order Traversal
2016-02-29 07:15
274 查看
Problem
Solution
关键点是想到怎样把每个点投影的横坐标上的位置表示出来 : 就是把root当做0 , 向左减1,向右加1写出来是这样
/** * 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 { void helper(TreeNode* root, int coord, map<int, vector<int>>& mp){ if(!root) return; mp[coord].push_back(root->val); helper(root->left, coord - 1, mp); helper(root->right, coord + 1, mp); } public: vector<vector<int>> verticalOrder(TreeNode* root) { map<int, vector<int>> mp; helper(root, 0, mp); vector<vector<int>> rst; for( auto it = mp.begin(); it != mp.end(); it++){ rst.push_back(it->second); } return rst; } };
没通过,有一个bug
5
1 6
3
2 4
就不能过关,因为先到 4, 将其坐标定位1,后来到了6,又发现1,这样顺序就成了 4, 6 而不是 6, 4
修改如下 :
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct VerNode { VerNode( int d, int v) : depth(d), val(v){} int depth; int val; }; bool cmp (const VerNode& n1, const VerNode& n2) { return n1.depth < n2.depth; } class Solution { void helper(TreeNode* root, int coord, int depth, map<int, vector<VerNode>>& mp){ if(!root) return; VerNode vn (depth, root->val); mp[coord].push_back(vn); helper(root->left, coord - 1, depth + 1, mp); helper(root->right, coord + 1,depth + 1, mp); } public: vector<vector<int>> verticalOrder(TreeNode* root) { map<int, vector<VerNode>> mp; helper(root, 0, 0, mp); vector<vector<int>> rst; for( auto it = mp.begin(); it != mp.end(); it++){ vector<VerNode> tempVN = it->second; sort(tempVN.begin(), tempVN.end(), cmp); vector<int> temp; for( auto vn : tempVN){ temp.push_back(vn.val); } rst.push_back(temp); } return rst; } };
相关文章推荐
- 命令行快速技巧:如何定位一个文件
- jquery+CSS实现的多级竖向展开树形TRee菜单效果
- cmd tree命令 以树形格式罗列文件
- 推荐8款jQuery轻量级树形Tree插件
- tree 以树形格式罗列文件
- EasyUI Tree+Asp.net实现权限树或目录树导航的简单实例
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- E3 tree 1.6在Firefox下显示问题的修复方法
- js树形控件脚本代码
- swing中Tree与滚动条用法实例分析
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- Spark Decision Tree
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- 带check的treeView
- Hadoop FS Shell
- DFS使用方法总结
- extjs 4 treepanel locked and expand
- JQuery EasyUI 实现tree的右键菜单
- FastDFS注意事项