Google
314 Binary Tree Vertical Order Traversal

1. Question

Given a binary tree, return thevertical ordertraversal 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:
  1. 1.
    Given binary tree[3,9,20,null,null,15,7],
    1
    3
    2
    /\
    3
    / \
    4
    9 20
    5
    /\
    6
    / \
    7
    15 7
    Copied!
    return its vertical order traversal as:
    1
    [
    2
    [9],
    3
    [3,15],
    4
    [20],
    5
    [7]
    6
    ]
    Copied!
  2. 2.
    Given binary tree[3,9,8,4,0,1,7],
    1
    3
    2
    /\
    3
    / \
    4
    9 8
    5
    /\ /\
    6
    / \/ \
    7
    4 01 7
    Copied!
    return its vertical order traversal as:
    1
    [
    2
    [4],
    3
    [9],
    4
    [3,0,1],
    5
    [8],
    6
    [7]
    7
    ]
    Copied!
  3. 3.
    Given binary tree[3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5),
    1
    3
    2
    /\
    3
    / \
    4
    9 8
    5
    /\ /\
    6
    / \/ \
    7
    4 01 7
    8
    /\
    9
    / \
    10
    5 2
    Copied!
    return its vertical order traversal as:
    1
    [
    2
    [4],
    3
    [9,5],
    4
    [3,0,1],
    5
    [8,2],
    6
    [7]
    7
    ]
    Copied!

2. Implementation

(1) BFS + HashMap
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
*/
10
class Solution {
11
public List<List<Integer>> verticalOrder(TreeNode root) {
12
List<List<Integer>> res = new ArrayList<>();
13
14
if (root == null) {
15
return res;
16
}
17
18
Queue<TreeNode> queue = new LinkedList<>();
19
Queue<Integer> distance = new LinkedList<>();
20
Map<Integer, List<Integer>> map = new HashMap<>();
21
int min = 0, max = 0;
22
23
queue.add(root);
24
distance.add(0);
25
26
while (!queue.isEmpty()) {
27
int size = queue.size();
28
29
for (int i = 0; i < size; i++) {
30
TreeNode curNode = queue.remove();
31
int curDistance = distance.remove();
32
33
map.putIfAbsent(curDistance, new ArrayList<>());
34
map.get(curDistance).add(curNode.val);
35
36
if (curNode.left != null) {
37
queue.add(curNode.left);
38
distance.add(curDistance - 1);
39
min = Math.min(min, curDistance - 1);
40
}
41
42
if (curNode.right != null) {
43
queue.add(curNode.right);
44
distance.add(curDistance + 1);
45
max = Math.max(max, curDistance + 1);
46
}
47
}
48
}
49
50
for (int i = min; i <= max; i++) {
51
res.add(map.get(i));
52
}
53
return res;
54
}
55
}
Copied!

3. Time & Space Complexity

BFS + HashMap:时间复杂度O(n),n为node的总个数, 空间复杂度O(n)