-
Notifications
You must be signed in to change notification settings - Fork 7
/
BST.java
175 lines (161 loc) · 2.62 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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package tree;
public class BST implements tree
{
static BSTNode root,hop,temp,print;
public BST()
{
root=null;
}
public void insert(Integer v)
{
BSTNode ob=new BSTNode(v);
if(root==null)
{
root=ob;
print=root;
}
else
{
hop=root;
while(true)
{
if(ob.val<=hop.val)
{
if(hop.left==null)
break;
hop=hop.left;
}
else
{
if(hop.right==null)
break;
hop=hop.right;
}
}
if(ob.val<=hop.val)
hop.left=ob;
else
hop.right=ob;
}
}
public void IOT(BSTNode print)
{
if(print!=null)
{
IOT(print.left);
System.out.print(print.val+" ");
IOT(print.right);
}
}
public void preOT(BSTNode print)
{
if(print!=null)
{
System.out.print(print.val+" ");
preOT(print.left);
preOT(print.right);
}
}
public void postOT(BSTNode print)
{
if(print!=null)
{
postOT(print.left);
postOT(print.right);
System.out.print(print.val+" ");
}
}
public BSTNode getRoot()
{
return root;
}
public BSTNode search(BSTNode print, Integer x)
{
if (print==null || print.val==x)
return print;
if (print.val>=x)
return search(print.left, x);
return search(print.right, x);
}
public void delete(Integer v)
{
temp=null;
if(search(print, v)==null)
{
System.out.println("element to be deleted not found!!");
return;
}
else
temp=search(print, v);
//to obtain parent
BSTNode parent=null;
hop=root;
while(true)
{
//System.out.println(hop.val+"\n"+hop);
if(hop.left==temp || hop.right==temp)
{
parent=hop;
break;
}
else if(v<hop.val)
hop=hop.left;
else if(v>hop.val)
hop=hop.right;
}
//0CN
if(temp.right==null && temp.right==null)
{
if(temp.val<=parent.val)
parent.left=null;
else
parent.right=null;
}
//1CN
else if(temp.left==null)
{
if(temp.val<=parent.val)
parent.left=parent.left.right;
else
parent.right=parent.right.right;
}
else if(temp.right==null)
{
if(temp.val<=parent.val)
parent.left=parent.left.left;
else
parent.right=parent.right.left;
}
//2CN
else if(temp.left!=null && temp.right!=null)
{
if(parent==null)
{
temp=root;
while(temp.right!=null)
{
temp.val=temp.right.val;
temp=temp.right;
}
temp=null;
}
if(temp.val<=parent.val)
{
parent.left.val=parent.left.right.val;
hop=parent.left.right;
}
else
{
parent.right.val=parent.right.right.val;
hop=parent.right.right;
}
while(hop.right.right!=null)
{
hop.val=hop.right.val;
hop=hop.right;
}
hop.val=hop.right.val;
hop.right=null;
}
}
}