forked from NATESHKUMAR485/Assignment_1_SE_Master-branch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BST.java
96 lines (86 loc) · 2.2 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
import java.util.Queue;
import java.util.LinkedList;
class node<T> {
T data;
node<T> left;
node<T> right;
node(T d){
data=d;
left = right = null;
}
}
public class BST<T extends Comparable<T>> {
node<T> root;
int count;
public void insert(T key)
{
node<T> n =new node<T>(key);
if(root==null)
{
root=n;
}
else{
node<T> temp=root;
node<T> prev=root;
while(temp!=null){
if (n.data.compareTo(temp.data) <= 0)
{
prev = temp;
temp = temp.left;
} else {
prev = temp;
temp = temp.right;
}
}
if (n.data.compareTo(prev.data) <= 0)
{
prev.left = n;
} else {
prev.right = n;
}
}
count++;
}
public void traverse(node n)
{
if ( root == null ){
return;
}
}
// public node find(T key){ … } // find key in a tree
void print(){
if (root == null) {
System.out.println("empty tree"); return;
}
Queue<node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
node temp = q.peek();
q.remove();
System.out.println(temp.data);
if (temp.left != null)
{
temp.left = (node) q;
System.out.println(temp.left.data);
}
else{
System.out.println(temp.left.data);
}
if (temp.right != null)
{
temp.right = (node) q;
System.out.println(temp.right.data);
}
else
System.out.println(temp.right.data);
}}
public static void main(String[] args) {
BST<Integer> bs = new BST<Integer>();
bs.insert(5);
bs.insert(9);
bs.insert(6);
bs.insert(4);
bs.insert(7);
bs.insert(8);
}
}