代码随想录Day22 | 235. 二叉搜索树的最近公共祖先、701. 二叉搜索树中的插入操作、450. 删除二叉搜索树中的节点 | 二叉树、递归、BST

42 阅读1分钟

235. 二叉搜索树的最近公共祖先

题目链接:235. 二叉搜索树的最近公共祖先

思路: 1、如果 p 和 q 都比当前节点小,那么显然 p 和 q 都在左子树,那么 LCA 在左子树。

2、如果 p 和 q 都比当前节点大,那么显然 p 和 q 都在右子树,那么 LCA 在右子树。

3、一旦发现 p 和 q 在当前节点的两侧,说明当前节点就是 LCA。

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        int val1 = Math.min(p.val, q.val);
        int val2 = Math.max(p.val, q.val);
        return find(root, val1, val2);
    }

    TreeNode find(TreeNode root, int val1, int val2) {
        if (root == null) {
            return null;
        }
        if (root.val > val2) {
            return find(root.left, val1, val2);
        }
        if (root.val < val1) {
            return find(root.right, val1, val2);
        }
        return root;
    }
}

总结:

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

题目链接:701. 二叉搜索树中的插入操作

思路: 虽然存在多种有效的插入方式,但是实际上一定可以在叶子节点插入,利用二叉搜索树的性质,当前节点大于目标值,遍历左子树,小于目标值,遍历右子树。

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);
        if (root.val > val) {
            root.left = insertIntoBST(root.left, val);
        } else if (root.val < val) {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }
}

总结:

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

题目链接:450. 删除二叉搜索树中的节点

思路:

情况 1:A 恰好是叶子节点,两个子节点都为空,那么直接删除即可。
情况 2:A 只有一个非空子节点,那么它要让这个孩子接替自己的位置。
情况 3:A 有两个子节点,为了不破坏 BST 的性质,A 必须找到左子树中最大的那个节点,或者右子树中最小的那个节点来接替自己。

TreeNode deleteNode(TreeNode root, int key) {
    if (root == null) return null;
    if (root.val == key) {
        // 这两个 if 把情况 1 和 2 都正确处理了
        if (root.left == null) return root.right;
        if (root.right == null) return root.left;
        // 处理情况 3
        // 获得右子树最小的节点
        TreeNode minNode = getMin(root.right);
        // 删除右子树最小的节点
        root.right = deleteNode(root.right, minNode.val);
        // 用右子树最小的节点替换 root 节点
        minNode.left = root.left;
        minNode.right = root.right;
        root = minNode;
    } else if (root.val > key) {
        root.left = deleteNode(root.left, key);
    } else if (root.val < key) {
        root.right = deleteNode(root.right, key);
    }
    return root;
}

TreeNode getMin(TreeNode node) {
    // BST 最左边的就是最小的
    while (node.left != null) node = node.left;
    return node;
}

总结: