先看一个需求 给你一个数组(7,3,10,12,5,1,9),要求能高效的完成对数据的查询的添加 解决方案分析 使用数组 数组未排序,优点:直接在数组尾添加,速度快。缺点:查找速度慢 数组排序:优点:可以使用二分查找,查找速度快。缺点:为了保证数组有序,在添加数据时,找到插入位置后,后面的数据需要整体移动,速度慢 使用链式储存-链表 不管链表是否有序,查找速度都很慢,添加数据速度比数组快,不需要数据整体移动 使用二叉排序树
二叉排序树介绍
二叉排序树:BST(Binary Sort(Search) Tree),对于二叉排序树的任何一个非叶子节点,要求左子节点的值比当前节点的值要小,右子节点的值要比当前节点的值要大 特别说明:如果有相同的值,可以将该节点放在左子节点或右子节点
二叉排序树遍历代码实现
class Nodes{
int value
;
Nodes left
;
Nodes right
;
public Nodes(int value
) {
super();
this.value
= value
;
}
@Override
public String
toString() {
return "Nodes [value=" + value
+ "]";
}
public void add(Nodes node
) {
if(node
==null) {
return;
}
if(node
.value
<this.value
) {
if(this.left
==null) {
this.left
=node
;
}else {
this.left
.add(node
);
}
}else {
if(this.right
==null) {
this.right
=node
;
}else {
this.right
.add(node
);
}
}
}
public void infixOrder() {
if(this.left
!=null) {
this.left
.infixOrder();
}
System
.out
.println(this);
if(this.right
!=null) {
this.right
.infixOrder();
}
}
}
class BinarySortTree{
private Nodes root
;
public void add(Nodes node
) {
if(root
==null) {
root
=node
;
}else {
root
.add(node
);
}
}
public void infixOrder() {
if(root
!=null) {
root
.infixOrder();
}else {
System
.out
.println("二叉排序树为空");
}
}
}
public static void main(String
[] args
) {
int
[]arr
= {7,3,10,12,5,1,9};
BinarySortTree binarySortTree
=new BinarySortTree();
for(int i
=0;i
<arr
.length
;i
++) {
binarySortTree
.add(new Nodes(arr
[i
]));
}
System
.out
.println("中序遍历二叉排序树~");
binarySortTree
.infixOrder();
}