forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearchTree.cs
148 lines (130 loc) · 3.93 KB
/
BinarySearchTree.cs
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
using System;
namespace BinarySearchTree
{
public class node
{
public int data;
public node left;
public node right;
public node(int d)
{
data = d;
left = null;
right = null;
}
}
class Program
{
node head;
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
{
Console.WriteLine("Element " + value + " Found");
return;
}
}
Console.WriteLine("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);
}
static void Main(string[] args)
{
Program x = new Program();
x.Insert(5);
x.Insert(7);
x.Insert(9);
x.Insert(8);
x.Insert(6);
x.Insert(4);
x.Search(9);
x.Search(2);
x.Delete(7);
x.Delete(5);
x.Delete(4);
x.Search(9);
x.Search(2);
x.Search(5);
x.Search(6);
Console.WriteLine();
Console.ReadLine();
}
}
}
/* Output
Element 9 Found
Element 2 not Found
Element 9 Found
Element 2 not Found
Element 5 not Found
Element 6 Found
*/