} else if (cpt > 0) {
// 如果key 小于 x的键,比较左子树 (递归)
x.left = delete(x.left, key);
} else {
// 如果相等,就找到了
// 元素数量减1
n–;
// 特殊情况:当前树x只有一个分叉,左或右
if (x.left == null) {
// 没有左子树,直接返回右子树即可
return x.right;
}
if (x.right == null) {
// 没有右子树,直接返回左子树即可
return x.left;
}
// 左右子树都存在
// 找出右子树中的最小结点minNode,并在右子树中删除minNode
Node minNode;
Node node = x.right;
while (node.left != null) {
// 移动minNode指针
minNode = node.left;
if (node.left.left == null) {
// 如果node.left没有下级结点,即为最小结点,设为null值,即为删除
node.left = null;
} else {
// 如果node.left有下级结点,移动node指针
node = node.left;
}
}
// 让被删除结点x的左子树成为minNode的左子树
minNode.left = x.left;
// 让被删除结点x的右子树(已删除minNode)成为minNode的右子树
minNode.right = x.right;
// 用minNode替换被删除结点x(被删除结点的父节点指向最小结点minNode)
x = minNode;
}
return x;
}
/**
-
获取树中元素个数
-
@return
*/
public int size() {
return n;
}
/**
- 内部结点类
*/
private class Node {
/**
- 键 key
*/
private K key;
/**
- 值 value
*/
private V value;
/**
- 左子结点
*/
private Node left;
/**
- 右子结点
*/
private Node right;
/**
-
构造器
-
@param key
-
@param value
-
@param left
-
@param right
*/
public Node(K key, V value, Node left, Node right) {
this.key = key;
this.value = value;
this.left = left;
this.right = right;
}
}
}
package chapter05;
import org.junit.Test;
/**
-
@author 土味儿
-
Date 2021/9/7
-
@version 1.0
-
测试二叉树
*/
public class BinaryTreeTest {
@Test
public void test(){
BinaryTree<Integer, String> bt = new BinaryTree<>();
bt.put(5,“张三”);
bt.put(2,“李四”);
bt.put(8,“王五”);
bt.put(6,“赵六”);
bt.put(3,“四七”);
System.out.println(“元素个数:”+bt.size());
bt.put(6,“秦八”);
System.out.println(“元素个数:”+bt.size());
bt.delete(8);
System.out.println(“删除后元素个数:”+bt.size());
System.out.println(bt.get(8));
}
}
元素个数:5
元素个数:5
删除后元素个数:4
null
4)二叉查找树其他便捷方法
1、查找二叉树中最小的键
-
API设计
-
递归方式
-
while循环方式
-
代码实现
/**
-
方法一:找出树中最小的键
-
while循环方式
-
@return
*/
public K min1() {
Node x = root;
if (x == null) {
return null;
}
while (x.left != null) {
x = x.left;
}
return x.key;
}
/**
-
方法二:找出树中最小的键
-
递归方式
-
@return
*/
public K min2() {
Node min = min(root);
if (min != null) {
return min.key;
}
return null;
//return min(root).key;
}
/**
-
找出树x中的最小键的结点
-
@param x
-
@return
*/
private Node min(Node x) {
if (x != null && x.left != null) {
//if (x.left != null) {
return min(x.left);
}
return x;
}
public class BinaryTreeTest {
@Test
public v