-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVerticalOrderTraversal.java
More file actions
64 lines (51 loc) · 1.37 KB
/
VerticalOrderTraversal.java
File metadata and controls
64 lines (51 loc) · 1.37 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
//This program implements vertical order traversal of a binary tree
import java.util.*;
class Node{
int val;
Node left;
Node right;
Node(int val){
this.val = val;
this.left = null;
this.right = null;
}
}
public class VerticalOrderTraversal{
static TreeMap<Integer, LinkedHashSet<Integer>> Map;
public static void verticaltraversal(Node root, int id){
if(Map.get(id) == null){
LinkedHashSet<Integer> S = new LinkedHashSet<Integer>();
S.add(root.val);
Map.put(id, S);
}
else{
Map.get(id).add(root.val);
}
if(root.left != null && root.right != null){
verticaltraversal(root.left, id+1);
verticaltraversal(root.right, id-1);
}
else if(root.left == null && root.right != null){
verticaltraversal(root.right, id-1);
}
else if(root.left != null && root.right == null){
verticaltraversal(root.left, id+1);
}
}
public static void main(String args[]){
Node root = new Node(1);
root.left = new Node(2);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right = new Node(3);
root.right.left = new Node(6);
root.right.left.right = new Node(8);
root.right.right = new Node(7);
root.right.right.right = new Node(9);
Map = new TreeMap<Integer, LinkedHashSet<Integer>>(Collections.reverseOrder());
verticaltraversal(root,0);
for(int id : Map.keySet()){
System.out.println(id + " " + Map.get(id));
}
}
}