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
|
//创建内部类Node,Node代表的就是树节点
public
static
class
Node{
int
key;
Node leftChild;
Node rightChild;
public
Node(
int
key){
this
.key=key;
this
.leftChild=
null
;
this
.rightChild=
null
;
}
public
Node(
int
key,Node leftChild,Node rightChild){
this
.key=key;
this
.leftChild=leftChild;
this
.rightChild=rightChild;
}
public
int
getKey(){
return
key;
}
@Override
public
boolean
equals(Object o){
Node node=(Node)o;
return
getKey() == node.key;
}
public
Node left(){
return
this
.leftChild;
}
public
Node right(){
return
this
.rightChild;
}
}
|
1
2
3
4
5
|
//成员变量以及构造函数
public
Node root;
public
BinarySearchTree(){
root=
null
;
}
|
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
|
public
boolean
isEmpty(){
return
root ==
null
?
true
:
false
;
}
public
void
makeEmpty(){
this
.root=
null
;
}
public
boolean
contains(
int
target,Node node){
if
(node ==
null
|| isEmpty()){
return
false
;
}
if
(target<node.key){
return
contains(target, node.leftChild);
}
else
if
(target>node.key){
return
contains(target,node.rightChild);
}
else
{
return
true
;
}
}
public
Node findMin(Node node){
if
(node==
null
|| isEmpty()){
return
null
;
}
if
(node!=
null
&& node.leftChild!=
null
) {
return
findMin(node.leftChild);
}
else
{
return
node;
}
}
public
Node findMax(Node node){
if
(node==
null
|| isEmpty()){
return
null
;
}
//这就是返回条件(递归结束条件)
if
(node.rightChild ==
null
)
return
node;
return
findMax(node.rightChild);
}
//整体思路就是插入哪一个节点,就返回哪一个节点
public
Node insert(
int
key,Node node){
if
(node==
null
){
//用于真实生成节点(递归结束条件)
return
new
Node(key,
null
,
null
);
}
else
if
(key < node.key){
//用于建立与左节点间的关联
node.leftChild=insert(key, node.leftChild);
}
else
if
(key > node.key){
//用于建立与右节点间的关联
node.rightChild=insert(key, node.rightChild);
}
else
;
return
node;
}
public
void
insert(
int
key){
root=insert(key,root);
}
//思路与插入思路差不多,删除那个节点就返回哪一个节点
public
Node remove(
int
key,Node node){
if
(node ==
null
)
return
null
;
if
(key < node.key){
node.leftChild=remove(key, node.leftChild);
}
else
if
(key > node.key){
node.rightChild=remove(key, node.rightChild);
}
//左右子树均非空
else
if
(node.leftChild !=
null
&& node.rightChild !=
null
){
//找到要移动的节点并替换掉,该过程出现新一轮的树枝生成过程
node.key=findMin(root.rightChild).key;
//这里负责新树枝的生成,因为这里要移动的是该节点的右分支,所以其实永远不会有删除动作发生,只会发生一点树枝的移动动作
node.rightChild=remove(node.key, node.rightChild);
}
//左子树或者右子树为空,此时node节点即为要删除的节点或者不存在的删除节点
else
{
node = (node.rightChild ==
null
) ? node.leftChild : node.rightChild;
}
return
node;
}
public
void
remove(
int
key){
root=remove(key, root);
}
|
以上就简单介绍了二人查找数的基本操作,当然用的是递归实现,但是也可以用到非递归的方法,这里不再给出。