forked from iharsh234/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BinarySearchTree.java
146 lines (124 loc) · 3 KB
/
BinarySearchTree.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
class BinarySearchTree
{
node head;
static class node
{
int data;
node left;
node right;
node(int d)
{
data = d;
left = null;
right = null;
}
}
public void Insert(int value)
{
node temp = new node(value);
if (head == null)
head = temp;
else
{
node current;
current = head;
while (current != null)
{
if (value < current.data)
{
if (current.left != null)
current = current.left;
else
{
current.left = temp;
return ;
}
}
else
{
if (current.right != null)
current = current.right;
else
{
current.right = temp;
return ;
}
}
}
}
}
public void Search(int value)
{
node current;
current = head;
while (current != null)
{
if (value < current.data)
current = current.left;
else if (value > current.data)
current = current.right;
else
{
System.out.println("Element " + value + " Found");
return ;
}
}
System.out.println("Element " + value + " not Found");
}
public int Min_Value(node head)
{
while (head.left != null)
head = head.left;
return head.data;
}
public node Delete_Key(node head, int value)
{
if (head == null)
return head;
if (value < head.data)
head.left = Delete_Key(head.left, value);
else if (value > head.data)
head.right = Delete_Key(head.right, value);
else
{
if (head.left == null)
return head.right;
else if (head.right == null)
return head.left;
head.data = Min_Value(head.right);
head.right = Delete_Key(head.right, head.data);
}
return head;
}
public void Delete(int value)
{
head = Delete_Key(head, value);
}
public static void main(String[] args)
{
BinarySearchTree BST = new BinarySearchTree();
BST.Insert(5);
BST.Insert(7);
BST.Insert(9);
BST.Insert(8);
BST.Insert(6);
BST.Insert(4);
BST.Search(9);
BST.Search(2);
BST.Delete(7);
BST.Delete(5);
BST.Delete(4);
BST.Search(9);
BST.Search(2);
BST.Search(5);
BST.Search(6);
}
}
/* Output
Element 9 Found
Element 2 not Found
Element 9 Found
Element 2 not Found
Element 5 not Found
Element 6 Found
*/