Given a binary tree,returnThe 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 20/ 15 7returnIts 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 7returnIts vertical order traversal as:[[4], [9], [3,5,2], [20], [7]]
Binary Tree Vertical order traversal. The meaning of this question is very simple, but the example is not good enough, if the second example above 5 also has the right subtree, and 20 in a column. In general it is assumed that a node column is I, then its left subtree column is i-1, right subtree column is i + 1.
Know this is good to do, we maintain a hashmap<integer, list<integer>>, key is the column number, List is the value of each TreeNode in that column, and then level Order traversal, add the corresponding node value to the corresponding key. We don't care about the specific column numbers, so it's good to root for 0 columns, and others to benchmark.
The point of the trickery is how to get the column number, we are here to use a queue, synchronous BFS; Other practices can do an internal class
Private class treecolumnnode{public TreeNode TreeNode; int col; Public Treecolumnnode (TreeNode node, int col) { this.treenode = node; This.col = col; }
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>> res =NewArraylist<list<integer>>(); - if(Root = =NULL)returnRes; -Hashmap<integer, arraylist<integer>> map =NewHashmap<integer, arraylist<integer>>(); thelinkedlist<treenode> queue =NewLinkedlist<treenode>(); -Linkedlist<integer> Colque =NewLinkedlist<integer>(); - Queue.offer (root); -Colque.offer (0); +Map.put (0,NewArraylist<integer>()); -Map.get (0). Add (root.val); + intMin=0, max=0; A while(!Queue.isempty ()) { atTreeNode cur =Queue.poll (); - intCol =Colque.poll (); - if(Cur.left! =NULL) { - Queue.offer (cur.left); -Colque.offer (col-1); - if(!map.containskey (col-1)) { inMap.put (COL-1,NewArraylist<integer>()); - } toMap.get (col-1). Add (cur.left.val); + if(Col-1 < min) min = col-1; - } the if(Cur.right! =NULL) { * Queue.offer (cur.right); $Colque.offer (col+1);Panax Notoginseng if(!map.containskey (col+1)) { -Map.put (Col+1,NewArraylist<integer>()); the } +Map.get (col+1). Add (cur.right.val); A if(Col+1 > Max) max = col + 1; the } + } - for(intK=min; k<=max; k++) { $ if(Map.containskey (k)) $Res.add (NewArraylist<integer>(Map.get (k))); - } - returnRes; the } -}
Leetcode:binary Tree Vertical Order traversal