[Locked] Binary Tree Vertical Order Traversal
2016-02-27 10:24
357 查看
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
return its vertical order traversal as:
Given binary tree
return its vertical order traversal as:
分析:
从根节点出发走的是一左一右或者一右一左的路径到达某节点,那么这个节点的列数可看做0;如果是两左,则为-2;为两右为2。
代码:
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] ]
分析:
从根节点出发走的是一左一右或者一右一左的路径到达某节点,那么这个节点的列数可看做0;如果是两左,则为-2;为两右为2。
代码:
void dfs(TreeNode *node, int col, vector<vector<int> > &vleft, vector<vector<int> > &vright) { if(!node) return; //在根节点右边 if(col > 0) { //列编号超出了vright边界,则扩展边界 while(col >= vright.size()) vright.push_back(vector<int> ()); vright[col].push_back(node->val); } //在根节点列左边或者中间 else { //列编号超出了vleft边界,则扩展边界 while(-col >= vleft.size()) vleft.push_back(vector<int> ()); vleft[-col].push_back(node->val); } dfs(node->left, col - 1, vleft, vright); dfs(node->right, col + 1, vleft, vright); return; } vector<vector<int> > verticalorder(TreeNode *root) { vector<vector<int> > vleft, vright; dfs(root, 0, vleft, vright); //翻转vleft,然后与vright拼接 reverse(vleft.begin(), vleft.end()); vleft.insert(vleft.end(), vright.begin() + 1, vright.end()); return vleft; }
相关文章推荐
- 分布式技术一周技术动态 2016.02.28
- BZOJ1565 植物大战僵尸
- apache AH00558 错误的解决
- 开机出现指令“Ox00000000”的内存,该内容不能为read解决方法
- 2016-2小笔记
- 视频播放器
- 微型投影仪:MSP430
- IP电话知识点与协议
- Java Sax解析xml
- 如何清除远程桌面连接的IP域名信息
- not in子查询的用法
- c++ virtual
- C语言书籍推荐
- H264编码原理以及I帧B帧P帧
- js 提示对话框知识
- (一)图像坐标:我想和世界坐标谈谈(A) 【计算机视觉学习笔记--双目视觉几何框架系列】
- ASP.NET 页面之间传递值的几种方式
- Linux如何查看JDK的安装路径
- 【leetcode】【6】ZigZag Conversion
- linux 网络连接