-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBinarySearchTree.java
124 lines (118 loc) · 2.21 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
import java.util.Comparator;
class BinarySearchTree<T>
{
private BSTNode root;
private Comparator <T>key;
private class BSTNode
{
T data;
BSTNode left,right;
@SuppressWarnings("unused")
int level;
BSTNode(T data)
{
this.data=data;
left=null;
right=null;
level=1;
}
public BSTNode getLeft()
{
return left;
}
public BSTNode getRight()
{
return right;
}
public int getLevel()
{
return level;
}
private void copy(BSTNode inorderPrecessor)
{
// TODO Auto-generated method stub
}
}
public BinarySearchTree(Comparator<T> key)
{
this.key=key;
root=null;
}
public void insert(T data)
{
root=insert(root,data);
}
private BSTNode insert(BSTNode root,T data)
{
if(root==null)
return new BSTNode(data);
else
{
if(key.compare(root.data, data)<0)
root.left=insert(root.left,data);
else
root.right=insert(root.right,data);
return root;
}
}
public int getLevel(T data)
{
return search(root, data).getLevel();
}
public BSTNode search(T data)
{
return search(root,data);
}
private BSTNode search(BSTNode root,T data)
{
int result=key.compare(root.data, data);
if(root==null||result==0)
return root;
else if(result<0)
return search(root.left,data);
else
return search(root.right,data);
}
public void remove(T data)
{
remove(root,data);
}
private BSTNode maxNode(BSTNode node)
{
while(node.right!=null)
node=node.right;
return node;
}
private BSTNode remove(BSTNode root,T data)
{
if(root==null)
return root;
int result=key.compare(root.data, data);
if(result<0)
{
root.left=remove(root.left, data);
}
else if(result>0)
{
root.right=remove(root.right, data);
}
else
{
if(root.left==null)
{
return root.right;
}
else if(root.right==null)
{
return root.left;
}
else
{
BSTNode inorderPrecessor=maxNode(root.left);
root.copy(inorderPrecessor);
root.left=remove(root.left, inorderPrecessor.data);
}
}
return root;
}
}