标签:
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] ]
分析:
For root, col = 0. The col of root‘s left child is root.col - 1, and the col of root‘s right child is root.col + 1.
1 public List<List<Integer>> verticalOrder(TreeNode root) { 2 List<List<Integer>> result = new ArrayList<List<Integer>>(); 3 if (root == null) 4 return result; 5 6 // level and list 7 HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); 8 9 LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); 10 LinkedList<Integer> level = new LinkedList<Integer>(); 11 12 queue.offer(root); 13 level.offer(0); 14 15 int minLevel = 0; 16 int maxLevel = 0; 17 18 while (!queue.isEmpty()) { 19 TreeNode p = queue.poll(); 20 int l = level.poll(); 21 22 // track min and max levels 23 minLevel = Math.min(minLevel, l); 24 maxLevel = Math.max(maxLevel, l); 25 26 if (map.containsKey(l)) { 27 map.get(l).add(p.val); 28 } else { 29 ArrayList<Integer> list = new ArrayList<Integer>(); 30 list.add(p.val); 31 map.put(l, list); 32 } 33 34 if (p.left != null) { 35 queue.offer(p.left); 36 level.offer(l - 1); 37 } 38 39 if (p.right != null) { 40 queue.offer(p.right); 41 level.offer(l + 1); 42 } 43 } 44 45 for (int i = minLevel; i <= maxLevel; i++) { 46 if (map.containsKey(i)) { 47 result.add(map.get(i)); 48 } 49 } 50 51 return result; 52 }
Reference:
http://www.cnblogs.com/yrbbest/p/5065457.html
http://www.programcreek.com/2014/04/leetcode-binary-tree-vertical-order-traversal-java/
Binary Tree Vertical Order Traversal
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5735216.html