-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathVerticalOrder.java
More file actions
70 lines (53 loc) · 1.43 KB
/
VerticalOrder.java
File metadata and controls
70 lines (53 loc) · 1.43 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
package Trees;
import java.util.*;
/**
* Author - archit.s
* Date - 04/11/18
* Time - 6:12 PM
*/
public class VerticalOrder {
class Pair{
TreeNode t;
int d;
Pair(TreeNode t, int d){
this.d = d;
this.t = t;
}
}
public ArrayList<ArrayList<Integer>> verticalOrderTraversal(TreeNode A) {
ArrayList<ArrayList<Integer>> r = new ArrayList<>();
Map<Integer, ArrayList<Integer> > map = new HashMap<>();
Queue<Pair> q = new LinkedList<>();
if(A == null){
return r;
}
int leftD = 0;
int rightD = 0;
Pair p = new Pair(A,0);
q.add(p);
while(!q.isEmpty()){
Pair pTemp = q.remove();
leftD = Math.min(leftD, pTemp.d);
rightD = Math.max(rightD, pTemp.d);
ArrayList<Integer> temp;
if(map.containsKey(pTemp.d)){
temp = map.get(pTemp.d);
}
else{
temp = new ArrayList<>();
}
temp.add(pTemp.t.val);
map.put(pTemp.d,temp);
if(pTemp.t.left!=null){
q.add(new Pair(pTemp.t.left, pTemp.d-1));
}
if(pTemp.t.right!=null){
q.add(new Pair(pTemp.t.right, pTemp.d+1));
}
}
for(int i=leftD;i<=rightD;i++){
r.add(map.get(i));
}
return r;
}
}