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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/delete-node-in-a-bst
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


分情况:
1,目标节点有一个孩子是null;那么就返回另外一个孩子,这里巧妙包含了孩子都是null的情况
2,目标节点左右孩子都有; 找到目标节点右子树中最小的值。与目标节点值替换,之后删除刚刚找的那个节点


    public TreeNode deleteNode(TreeNode root, int key) {
        if(root == null) {
            return null;
        }

        if(root.val < key) {
            // 从右孩子查找
            root.right = deleteNode(root.right, key);
        } else if(root.val > key) {
            // 从左孩子查找
            root.left = deleteNode(root.left, key);

        } else {
            // 找到了
            // 左孩子为null就返回右孩子
            TreeNode left = root.left;
            if(left == null) {
                return root.right;
            }

            // 右孩子为null,就返回左孩子
            TreeNode right = root.right;
            if(right == null) {
                return root.left;
            }

            // 如果都不为null,就从右孩子找最小的的值。替换,之后删除右孩子节点中最小的那个节点

            TreeNode min = getMin(root.right);
            int tmp = min.val;
            min.val = root.val;
            root.val = tmp;
            root.right = deleteNode(root.right,min.val);
            return root;


        }

        return root;

    }

    public TreeNode getMin(TreeNode node) {
        TreeNode cur = node;

        while(cur != null && cur.left != null) {
            cur = cur.left;
        }
        return cur;
    }
posted @ 2022-02-27 11:40  一颗青菜  阅读(4)  评论(0)    收藏  举报