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 class Solution {
2 public List<List<Integer>> verticalOrder(TreeNode root) {
3 List<List<Integer>> res = new ArrayList<>();
4 if (root == null) return res;
5
6 Map<Integer, ArrayList<Integer>> map = new HashMap<>();
7 Queue<Pair<TreeNode, Integer>> q = new LinkedList<>();
8
9 q.add(new Pair(root, 0));
10
11 int min = 0, max = 0;
12
13 while (!q.isEmpty()) {
14 Pair<TreeNode, Integer> pair = q.poll();
15 TreeNode node = pair.getKey();
16 int col = pair.getValue();
17
18 if (!map.containsKey(col)) {
19 map.put(col, new ArrayList<>());
20 }
21 map.get(col).add(node.val);
22
23 if (node.left != null) {
24 q.offer(new Pair(node.left, col - 1));
25 min = Math.min(min, col - 1);
26 }
27
28 if (node.right != null) {
29 q.offer(new Pair(node.right, col + 1));
30 max = Math.max(max, col + 1);
31 }
32 }
33
34 for (int i = min; i <= max; i++) {
35 res.add(map.get(i));
36 }
37
38 return res;
39 }
40 }