定义

任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树;
没有键值相等的节点。

特点

插入删除查找的平均复杂度都是O(log n),当节点有序的时候退化成链表O(n)复杂度(树的全部结点都只有左/右子树)

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
public class BinaryTree implements ITree {
Node root;

public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
binaryTree.insert(4, 2);
binaryTree.insert(3, 23423);
binaryTree.insert(2, 234);
binaryTree.display(binaryTree.root);
}

public void display(Node node) {
if (node != null) {
System.out.println(node.id + " " + node.data);
}
if (node.left != null) {
display(node.left);
}
if (node.right != null) {
display(node.right);
}
}

public void insert(int id, Object data) {
Node node = new Node();
node.id = id;
node.data = data;
insert(node);
}

public void insert(Node node) {
if (root == null) {
root = node;
return ;
}

Node currentNode = root;
while (true) {
if (node.id < currentNode.id) {
currentNode = currentNode.left;
if (currentNode == null) {
currentNode = node;
}
} else if (node.id > currentNode.id) {
currentNode = currentNode.right;
if (currentNode == null) {
currentNode = node;
}
} else {
currentNode = node;
break;
}
}

}

public Node max(){
Node currentNode;
if(root!=null){
currentNode = root;
}else{
return null;
}
while(true){
if(currentNode.right!=null){
currentNode = currentNode.right;
}else{
return currentNode;
}
}
}

public Node min(){
Node currentNode;
if(root!=null){
currentNode = root;
}else{
return null;
}
while(true){
if(currentNode.left!=null){
currentNode = currentNode.left;
}else{
return currentNode;
}
}
}

public Node find(int key) {
Node currentNode = root;
while (currentNode.id != key) {
if (currentNode.id > key) {
currentNode = currentNode.left;
} else if (currentNode.id < key) {
currentNode = currentNode.right;
}
if (currentNode == null) {
return null;
}

}
return currentNode;
}

}