[Locked] Binary Tree Vertical Order Traversal
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Locked] Binary Tree Vertical Order Traversal相关的知识,希望对你有一定的参考价值。
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] ]
分析:
从根节点出发走的是一左一右或者一右一左的路径到达某节点,那么这个节点的列数可看做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; }
以上是关于[Locked] Binary Tree Vertical Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章
Binary Tree和Binary Search Tree
[Leetcode] Binary tree-- 606. Construct String from Binary Tree
[Leetcode] Binary search tree --Binary Search Tree Iterator
[数据结构]Binary_tree | Binary_search_tree | avl_tree
[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree