-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathverticalOrder3.java
54 lines (41 loc) · 1.28 KB
/
verticalOrder3.java
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
static int min=0, max=0;
static void findminmax(TreeNode root, int h) {
if(root == null) return;
min = Math.min(min, h);
max = Math.max(max, h);
findminmax(root.left, h-1);
findminmax(root.right, h+1);
}
static class Pair {
TreeNode node;
int level;
public Pair(TreeNode node, int level) {
this.node = node;
this.level = level;
}
}
static class thecomparator implements Comparator<Pair> {
public int compare(Pair p1, Pair p2) {
return p1.node.val - p2.node.val;
}
}
public static ArrayList<ArrayList<Integer>> verticalOrderTraversal(TreeNode root) {
findminmax(root, 0);
ArrayList<ArrayList<Integer>> ans= new ArrayList<>();
for(int i=0; i<max-min+1; i++) {
ans.add(new ArrayList<>());
}
PriorityQueue<Pair> mq = new PriorityQueue<>(new thecomparator());
Queue<Pair> cq = new LinkedList<>();
mq.add(new Pair(root, -min));
while(!mq.isEmpty()) {
Pair p = mq.remove();
ans.get(p.level).add(p.node.val);
if(p.node.left != null) cq.add(new Pair(p.node.left, p.level-1));
if(p.node.right != null) cq.add(new Pair(p.node.right, p.level+1));
if(mq.size() == 0) {
while(!cq.isEmpty()) mq.add(cq.poll());
}
}
return ans;
}