-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathBottomView.java
126 lines (115 loc) · 2.77 KB
/
BottomView.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import java.util.*;
import java.util.Map.*;
import java.util.Queue;
abstract class BottomView
{
/**
* BINARY TREE NODE STRUCTURE
**/
private static class BTNode
{
private int data;
private BTNode left;
private BTNode right;
//constructors
public BTNode(int data)
{
this.data=data;
}
//getters
public BTNode getLeft()
{
return left;
}
public BTNode getRight()
{
return right;
}
public int getData()
{
return data;
}
//setters
public void setLeft(BTNode left)
{
this.left = left;
}
public void setRight(BTNode right)
{
this.right = right;
}
}
/**
* BOTTOM VIEW OF A TREE
**/
public static void bottomview(BTNode root)
{
/**
* NEW quenode CLASS FOR A QUEUE
**/
final class quenode
{
public BTNode data;
public int hd;
public quenode(BTNode data,int hd)
{
this.data = data;
this.hd = hd;
}
}
Queue<quenode> Q = new LinkedList<quenode>();
Q.add(new quenode(root,0));
Map<Integer,Integer> m = new TreeMap<Integer,Integer>();
while(!Q.isEmpty())
{
quenode temp = Q.poll();
m.put(temp.hd, temp.data.getData());
if(temp.data.getLeft()!=null)
{
Q.add(new quenode(temp.data.getLeft(),temp.hd-1));
}
if(temp.data.getRight()!=null)
{
Q.add(new quenode(temp.data.getRight(),temp.hd+1));
}
}
//traversing the map
for(Entry<Integer,Integer> entry: m.entrySet())
{
System.out.print(entry.getValue()+" ");
}
System.out.println();
}
/**
* TREE EXAMPLE GIVEN
* 20 <- ROOT
* / \
* 8 22
* / \ \
* 5 3 25
* / \
* 10 14
*
* BOTTOM VIEW : 5 10 3 14 25
* */
public static void main(String[] args)
{
BTNode a = new BTNode(20);
BTNode b = new BTNode(8);
BTNode c = new BTNode(22);
BTNode d = new BTNode(5);
BTNode e = new BTNode(3);
BTNode f = new BTNode(25);
BTNode g = new BTNode(10);
BTNode h = new BTNode(14);
BTNode root = a;
a.setLeft(b);
a.setRight(c);
b.setLeft(d);
b.setRight(e);
e.setLeft(g);
e.setRight(h);
c.setRight(f);
bottomview(root);
}
}