数据结构与算法-04二叉树-03

构建二叉搜索树

添加节点

public TreeNode insert(TreeNode root, int val) {
    TreeNode newNode = new TreeNode(val);
    if (root == null) {
        root = newNode;
        return root;
    }

    if (val < root.val) {
        root.left = insert(root.left, val);
    } else {
        root.right = insert(root.right, val);
    }
    return root;
}

删除节点

递归方式查找节点是否是要删除的节点

跳出条件: 如果是叶节点,即left,right为null 删终止

image-20241204140904818

image-20241129170428903

Hibbard Deletion:One efficient way to do this, as discovered by Thomas Hibbard in 1962, is to swap the node to be deleted with its successor. The successor to a key is the next largest key in the tree and is conveniently found as the minimum key in the right subtree of the node to be deleted.

image-20241204141848592

image-20241204142738685

 public TreeNode remove(TreeNode root, int val) {

        if (root.val == val) { //找到节点
            //要删除的节点是叶节点
            if (root.left == null && root.right == null) {
                return null;
            }
            //要删除的节点只有右节点
            if (root.left == null) {
                return root.right;
            }
            //要删除的节点只有左节点
            if (root.right == null) {
                return root.left;
            }
            //要删除的节点左右都不为空
            //找到当前节点的子树中的最小节点
            TreeNode minNode = minNode(root.right);
            minNode.right = remove(root.right, minNode.val);
            minNode.left = root.left;
            return minNode;
        } else if (val < root.val) {
            root.left = remove(root.left, val);
        } else {
            root.right = remove(root.right, val);
        }
        return root;
    }

查询

public void print(TreeNode root){
    if(root == null) return;
    print(root.left);
    System.out.print(root.val+"\t");
    print(root.right);
}

测试

public static void main(String[] args) {
        BstTree tree = new BstTree();
        TreeNode root = tree.insert(null, 15);
        root = tree.insert(root, 8);
        root = tree.insert(root, 25);
        root = tree.insert(root, 5);
        root = tree.insert(root, 12);
        root = tree.insert(root, 20);
        root = tree.insert(root, 55);

        tree.print(root);
        System.out.println();
        tree.remove(root, 15);
        tree.print(root);

    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值