文章目录
二叉排序树(Binary Sort Tree),又称为二叉查找树
特点:
若它的左子树不为空,则左子树上的所有结点的值均小于它的根结点的值。同理,右子树是大于根结点的值。它的左、右子树也分别为二叉排序树。
注: 若有相同的值,将该结点放在左子结点或右子结点均可(本文放在右子结点)
一、二叉排序树的插入(即二叉树的创建)
(1)步骤
- 若二叉排序树为空树,则新插入的结点为新的根结点。
- 若不为空树,且新结点的值 < 当前结点的值,且当前结点无左结点,则插入新结点(成为当前结点的左结点)。
- 否则,递归当前结点的左结点。
- 若新结点的值 > 当前结点的值,且当前结点无右结点,则插入新结点(成为当前结点的右结点)。
- 否则,递归当前结点的右结点。
(2)实现代码
- Node类的插入函数
public void add(Node node){ //插入结点的方法
if(node != null){
if(node.value < this.value){ //1.若新结点的值 < 当前结点
if(this.left == null){ //1.1当前结点无左结点
this.left = node; //新结点成为当前结点的左结点
}else { //1.2若当前结点有左结点
this.left.add(node); //递归左结点
}
} else if(this.right == null){ //2.若新结点的值>=当前结点,且当前结点无右结点
this.right = node; //2.1新结点成为当前结点的右结点
}else{ //2.2当前结点有右结点
this.right.add(node); //递归右结点
}
}
}
- BinarySortTree类的插入函数
public void add(Node node ){ //二叉排序树插入结点的方法
if(root == null){ //1.若根结点为空
root = node; //1.1把输入的结点放在根结点
}else{ //2.若根结点不为空
root.add(node); //2.1调用Node类中的添加结点的方法
}
}
二、二叉排序树的遍历
和普通二叉树一样,也有前序、中序、后续遍历。这里代码实现了中序遍历。
(1)代码实现
- Node类的中序遍历函数
public void infixOrder(){ //树的中序遍历
if(this.left != null){ //1.若当前结点有左结点
this.left.infixOrder(); //1.1递归该左结点
}
System.out.println(this.value); //2.一直递归到结点无左子结点。并输出这个结点
if(this.right != null){ //3.若当前有右结点
this.right.infixOrder(); //3.1递归该右结点(当右结点无左结点时,该右结点也会被2.1输出)
}
}
- BinarySortTree类的中序遍历函数
public void infixOrder() {
if(this.root != null) {
this.root.infixOrder();
} else {
System.out.println("二叉排序树为空,不能遍历");
}
}
三、二叉排序树的查找
(1)步骤
二叉排序树可看作一个有序表,它的查找类似与二分查找。
- 若查找的关键字 = 根结点关键字,查找成功。
- 若查找的关键字 < 根结点关键字,递归查找左子树。
- 若查找的关键字 > 根结点关键字,递归查找右子树。
- 若子树为空,则查找失败。
(2)实现代码
- Node类的查找函数
public Node BstSearch(int num){ //结点的查找
if(num == this.value){ //1.若查找的值 = 当前结点的值
return this; //1.1返回当前节点的索引
}else if(num < this.value && this.left != null){ //2.若查找的值 < 当前结点的值
return this.left.BstSearch(num); //2.1递归查找当前结点的左子结点
}else if(num > this.value && this.right != null){ //3.若查找的值 > 当前结点的值
return this.right.BstSearch(num); //3.1递归查找当前结点的右子结点
}
return null; //若没查到,则返回索引null
}
- BinarySortTree类的查找函数
public Node BstSearch(int num){ //树中的结点查找
if(num == root.value){ //1.若要查找的值正好 = 根结点的值
return root; //1.1返回根结点的索引
}else{ //2.若要查找的值 != 根结点的值
return roo