Given a binary tree, return the vertical order Traversal of its nodes ' values. (ie, from top to bottom, and column by column).
If the nodes is in the same row and column, the order should is from left to right.
Examples:
- Given binary Tree
[3,9,20,null,null,15,7]
,
3 // 9 / / 7
Return its vertical order traversal as:
[ 9], [3,15], [+], [7]]
- Given binary Tree
[3,9,8,4,0,1,7]
,
3 / / 9 8 /\ // / 4 7
Return its vertical order traversal as:
[ 4], [9], [3,0,1], [8], [7]]
- Given binary Tree
[3,9,8,4,0,1,7,null,null,null,2,5]
(0 ' s right child was 2 and 1 ' s left child is 5),
3 / / 9 8 /\ // / 4 7 / / 5 2
Return its vertical order traversal as:
[ 4], [9,5], [3,0,1], [8,2], [7]]
Analysis:note in the second example, 2 was in the left subtree of root, but would after 8 in the results. So simple traverse. We can use the BFS with index recording. Solution:
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One PublicList<list<integer>>Verticalorder (TreeNode root) { AList<list<integer>> reslist =NewArraylist<list<integer>>(); - if(root==NULL)returnreslist; - theList<treenode> nodeList =NewArraylist<treenode>(); -List<integer> indexlist =NewArraylist<integer>(); - intCur = 0, min = 0, max=0; - Nodelist.add (root); +Indexlist.add (0); - + while(cur<nodelist.size ()) { ATreeNode Curnode =nodelist.get (cur); at intCurindex =indexlist.get (cur); - if(Curindex < min) min =Curindex; - if(Curindex > Max) max =Curindex; - - if(curnode.left!=NULL){ - Nodelist.add (curnode.left); inIndexlist.add (curIndex-1); - } to if(curnode.right!=NULL){ + Nodelist.add (curnode.right); -Indexlist.add (curindex+1); the } *cur++; $ }Panax Notoginseng - for(inti=min;i<=max;i++) Reslist.add (NewLinkedlist<integer>()); the + for(intI=0;i<nodelist.size (); i++){ AReslist.get (Indexlist.get (i)-min). Add (Nodelist.get (i). val); the } + - $ returnreslist; $ } - -}
Leetcode-binary Tree Vertical Order traversal