-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeVerticalOrderTraversal.java
More file actions
50 lines (46 loc) · 1.48 KB
/
Copy pathBinaryTreeVerticalOrderTraversal.java
File metadata and controls
50 lines (46 loc) · 1.48 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private class Node {
TreeNode node;
int col;
public Node(TreeNode n, int c) {
node = n;
col = c;
}
}
public List<List<Integer>> verticalOrder(TreeNode root) {
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
Queue<Node> q = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
int min = 0, max = 0;
q.add(new Node(root, 0));
while (!q.isEmpty()) {
Node n = q.remove();
min = Math.min(min, n.col);
max = Math.max(max, n.col);
if (map.containsKey(n.col)) {
map.get(n.col).add(n.node.val);
} else {
List<Integer> l = new ArrayList<>();
l.add(n.node.val);
map.put(n.col, l);
}
if (n.node.left != null) q.add(new Node(n.node.left, n.col - 1));
if (n.node.right != null) q.add(new Node(n.node.right, n.col + 1));
}
for (int i = min; i <= max; i++) {
List<Integer> l = map.get(i);
if (l != null) res.add(l);
}
return res;
}
}