-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.java
154 lines (130 loc) · 2.66 KB
/
BST.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BST
{
private int value;
private BST lNode;
private BST rNode;
public int getValue()
{
return value;
}
public void setValue(int value)
{
this.value = value;
}
public BST getlNode()
{
return lNode;
}
public void setlNode(BST lNode)
{
this.lNode = lNode;
}
public BST getrNode()
{
return rNode;
}
public void setrNode(BST rNode)
{
this.rNode = rNode;
}
public void insert(BST hNode, BST iNode)
{
if(iNode.getValue() <= hNode.getValue())
{
//insert on left side of the tree
if(hNode.getlNode() == null)
{
hNode.setlNode(iNode);
}
else
{
insert(hNode.getlNode(), iNode);
}
}
else
{
//insert to the right of the tree
if(hNode.getrNode() == null)
{
hNode.setrNode(iNode);
}
else
{
insert(hNode.getrNode(), iNode);
}
}
}
public boolean find(int n)
{
boolean retVal = false;
return retVal;
}
public void BFT(BST hNode)
{
Queue<BST> tracker = new LinkedList<BST>();
tracker.add(hNode);
while(!tracker.isEmpty())
{
BST cN = tracker.remove();
System.out.print(" "+cN.getValue());
if(cN.getlNode() != null)
tracker.add(cN.getlNode());
if(cN.getrNode() != null)
tracker.add(cN.getrNode());
}
}
public void DFT(BST hNode)
{
if(hNode == null)
return;
//in order traversal
DFT(hNode.getlNode());
System.out.print(" "+ hNode.getValue());
DFT(hNode.getrNode());
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BST hNode = new BST();
hNode.setValue(Integer.MIN_VALUE);
hNode.setlNode(null);
hNode.setrNode(null);
Scanner sc = new Scanner(System.in);
String input = "";
while(true)
{
System.out.print("Enter number to insert or E to exit: ");
input = sc.nextLine();
if(input.equals("E"))
break;
try {
int in = Integer.parseInt(input);
if(hNode.getValue() == Integer.MIN_VALUE)
{
hNode.setValue(in);
}
else
{
BST iNode = new BST();
iNode.setValue(in);
iNode.setlNode(null);
iNode.setrNode(null);
hNode.insert(hNode, iNode);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.print("Input error \n");
//e.printStackTrace();
}
}
System.out.println("Bredth first travesal");
hNode.BFT(hNode);
System.out.println("\nDepth first traversal (in order)");
hNode.DFT(hNode);
}
}