leetcode 700 & 701 & 450 BST 的查、增、删

labuladong

题目链接:

leetcode 700. 二叉搜索树中的搜索

本题思路:
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if(root == null) return null;

        if(root.val == val) return root;
        else if(val > root.val) 
            return searchBST(root.right, val);
        else
            return searchBST(root.left, val);
    }
}
题目链接:

leetcode 701. 二叉搜索树中的插入操作

本题思路:
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null) return new TreeNode(val);
        if(val > root.val) {
            root.right = insertIntoBST(root.right, val);
        }
        if(val < root.val) {
            root.left = insertIntoBST(root.left, val);
        }
        return root;
    }
}
题目链接:

leetcode 450. 删除二叉搜索树中的节点

本题思路:
class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        // 1 根为空
        if(root == null) return null;
        // 2 根不空
        // 2.1 根为key
        if(root.val == key) {
            // 2.1.0 左右孩子都为null 以下两种情况包含这种情况
            // 2.1.1 左孩子null 则右孩子接替自己位置
            if(root.left == null) return root.right;
            // 2.1.2 右孩子null 则左孩子接替自己位置
            if(root.right == null) return root.left;
            // 2.1.3 左右孩子都不为null 左孩子中的max或右孩子中的min接替自己位置
            TreeNode minNode = min(root.right);
            minNode.right = deleteMin(root.right);
            minNode.left = root.left;
            return minNode;           
        }
        // 2.2 key > 根
        if(key > root.val) {
            root.right = deleteNode(root.right, key);
        }
        // 2.3 key < 根
        if(key < root.val) {
            root.left = deleteNode(root.left, key);
        }
        return root;
    }

    private TreeNode min(TreeNode node) {
        // BST最左侧的节点最小
        while (node.left != null) {
            node = node.left;
        }
        return node;
    }

    private TreeNode deleteMin(TreeNode node) {
        if(node.left == null) return node.right;
        node.left = deleteMin(node.left);
        return node;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值