-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path651.binary-tree-vertical-order-traversal.java
More file actions
71 lines (58 loc) · 1.78 KB
/
651.binary-tree-vertical-order-traversal.java
File metadata and controls
71 lines (58 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: the root of tree
* @return: the vertical order traversal
*/
Map<TreeNode, Integer> map = new HashMap<>();
int minCol = Integer.MAX_VALUE;
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if (root == null) {
return ans;
}
// dfs generate the column index:
// go left -> index - 1, go right -> index + 1
dfs(root, 0);
// bfs guarantee the top to bottom, and left to right order
bfs(root, map, ans);
return ans;
}
private void dfs(TreeNode root, int col) {
if (root == null) {
return ;
}
dfs(root.left, col - 1);
dfs(root.right, col + 1);
map.put(root, col);
minCol = Math.min(minCol, col);
}
private void bfs(TreeNode root, Map<TreeNode, Integer> map, List<List<Integer>> ans) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
TreeNode head = q.poll();
if (head.left != null) {
q.offer(head.left);
}
if (head.right != null) {
q.offer(head.right);
}
int col = map.get(head) - minCol;
while (ans.size() <= col) {
ans.add(new ArrayList<>());
}
ans.get(col).add(head.val);
}
}
}