手写 BST 二叉查找树

思路之前一直觉得二叉查找树写起来比较麻烦,主要是添加删除元素比较复杂抽象,这次写了一下其实还好。删除某个元素,只需要把右子树中最小节点和待删除元素交换,并删除最后那个字节点。(右子树最小节点刚好比左子树所有节点大,比右子树所有节点小,故符合要求)。这么一思考,代码挺简单的。Codepublic class BST {TreeNode root;TreeNode makeEmpty(TreeNode t) { if (t == null) return null; makeEmpt
摘要由CSDN通过智能技术生成

思路

之前一直觉得二叉查找树写起来比较麻烦,主要是添加删除元素比较复杂抽象,这次写了一下其实还好。删除某个元素,只需要把右子树中最小节点和待删除元素交换,并删除最后那个字节点。(右子树最小节点刚好比左子树所有节点大,比右子树所有节点小,故符合要求)。这么一思考,代码挺简单的。

Code


public class BST {

    TreeNode root;

    TreeNode makeEmpty(TreeNode t) {
        if (t == null) return null;
        makeEmpty(t.left);
        makeEmpty(t.right);
        t = null;
        return null;
    }

    TreeNode insert(TreeNode t, int val) {
        if (t == null) {
            t = new TreeNode(val);
        } else if (val < t.val) {
            t.left = insert(t.left, val);
        } else if (val > t.val) {
            t.right = insert(t.right, val);
        }
        return t;
    }

    TreeNode find(TreeNode t, int val) {
        if (t == null) return null;
        if (val < t.val) {
            return find(t.left, val);
        } else if (val > t.val) {
            return find(t.right, val);
        }
        return t;
    }

    TreeNode findMin(TreeNode t) {
        if (t == null || t.left == null) return t;
        return findMin(t.left);
    }

    TreeNode findMax(TreeNode t) {
        if (t == null || t.right == null) return t;
        return findMax(t);
    }

    TreeNode remove(TreeNode t, int val) {
        TreeNode temp;
        if (t == null) return null;
        else if (val < t.val) t.left = remove(t.left, val);
        else if (val > t.val) t.right = remove(t.right, val);
        else if (t.left != null && t.right != null) {
            temp = findMin(t.right);
            t.val = temp.val;
            t.right = remove(t.right, t.val);
        } else {
            temp = t;
            if (t.left == null) t = t.right;
            else if (t.right == null) t = t.left;
            temp = null;
        }
        return t;
    }

    public BST() {
        root = null;
    }

    void insert(int v) { insert(root, v); }

    void remove(int v) { remove(root, v); }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值