用了treemap来维护左右关系,其实也可以不用,记录一个min的index就好。
public class Solution { public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if (root == null) { return result; } HashMap<TreeNode, Integer> map1 = new HashMap<TreeNode, Integer>(); TreeMap<Integer, List<Integer>> map2 = new TreeMap<Integer, List<Integer>>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); map1.put(root, 0); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); int index = map1.get(node); List<Integer> list = map2.containsKey(index) ? map2.get(index) : new ArrayList<Integer>(); list.add(node.val); map2.put(index, list); if (node.left != null) { queue.offer(node.left); map1.put(node.left, index - 1); } if (node.right != null) { queue.offer(node.right); map1.put(node.right, index + 1); } } } Iterator<Integer> it = map2.keySet().iterator(); while (it.hasNext()) { result.add(map2.get(it.next())); } return result; } }