-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.java
156 lines (138 loc) · 3.48 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
155
156
class Node {
int value;
Node left;
Node right;
Node(int v) {
value = v;
left = null;
right = null;
}
}
class BST {
Node root;
BST() {
root = null;
}
void insert(int data) {
if (root == null) {
root = new Node(data);
return;
}
Node parent = null, current = root;
while (current != null) {
parent = current;
if (data < current.value) {
current = current.left;
} else {
current = current.right;
}
}
if (data < parent.value) {
parent.left = new Node(data);
} else {
parent.right = new Node(data);
}
}
void inorder() {
inorderRec(root);
}
void inorderRec(Node n) {
if (n != null) {
inorderRec(n.left);
System.out.print(" " + n.value);
inorderRec(n.right);
}
}
void delete(int data) {
root = deleteRec(root, data);
}
Node findMin(Node n) {
if (n != null) {
while (n.left != null) {
n = n.left;
}
}
return n;
}
Node findMax(Node n) {
if (n != null) {
while (n.right != null) {
n = n.right;
}
}
return n;
}
Node deleteRec(Node r, int d) {
// if root is empty
if (r == null) {
return null;
}
// if node is in leftsubtree
if (d < r.value) {
r.left = deleteRec(r.left, d);
} else if (d > r.value) {
// if node is in right subtree
r.right = deleteRec(r.right, d);
}
// if node is found
else {
// no left & right child
if (r.left == null && r.right == null) {
r = null;
return r;
}
// if only left child
else if (r.right == null) {
return r.left;
}
// if only right child
else if (r.left == null) {
return r.right;
}
// if both children left & right child
else {
// find succesor using findmin
r.value = findMin(r.right).value;
/// delete succesor
r.right = deleteRec(r.right, r.value);
}
}
return r;
}
void search(Node n, int data) {
if (n == null) {
System.out.println("Tree Is Empty..");
return;
}
while (n != null) {
if (n.value == data) {
System.out.println("Element Found: " + data);
return;
} else if (data < n.value) {
n = n.left;
} else {
n = n.right;
}
}
System.out.println("Element not found !!");
}
public static void main(String[] args) {
BST b = new BST();
b.insert(5);
b.insert(10);
b.insert(2);
b.inorder(); // 2,5,10
System.out.println("Inserting 25,20,30");
b.insert(25);
b.insert(20);
b.insert(30);
b.inorder();
b.delete(30);
System.out.println("Deleting 30");
b.inorder();
System.out.println("Max Element:");
Node max = b.findMax(b.root);
System.out.println(max.value);
b.search(b.root, 25);
}
}