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

递归

class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {

        if (root == null){
            return root;
        }

        /**
         * 如果大于当前节点,就在左子树寻找;小于则在右子树寻找
         * 相等则分三种情况:如果有一个孩子为空,则让另一个孩子作为新的根节点;否则,让左子树的最小节点成为新的根节点
         */
        if (root.val > key){

            root.left = deleteNode(root.left, key);

            return root;
        }
        else if (root.val < key){

            root.right = deleteNode(root.right, key);

            return root;
        }
        else {

            if (root.left == null){

                TreeNode right = root.right;
                root.right = null;

                return right;
            }
            else if (root.right == null){

                TreeNode left = root.left;
                root.left = null;

                return left;
            }
            else {

                TreeNode newRoot = findMin(root.right);
                newRoot.right = removeMin(root.right);
                newRoot.left = root.left;
                root.left = null;
                root.right = null;

                return newRoot;
            }
        }
    }

    /**
     * 寻找最小节点
     */
    public TreeNode findMin(TreeNode root){

        if (root == null){
            return root;
        }

        if (root.left == null){
            return root;
        }

        return findMin(root.left);
    }

    /**
     * 删除最小节点
     */
    public TreeNode removeMin(TreeNode root){

        if (root == null){
            return root;
        }

        if (root.left == null){

            TreeNode right = root.right;
            root.right = null;

            return right;
        }
        else {

            root.left = removeMin(root.left);

            return root;
        }
    }
}

/**
 * 时间复杂度 O(logn)
 * 空间复杂度 O(logn)
 */

https://leetcode-cn.com/problems/delete-node-in-a-bst/

posted @ 2022-01-05 17:30  振袖秋枫问红叶  阅读(41)  评论(0)    收藏  举报