【Lintcode】87. Remove Node in Binary Search Tree

Title address:

https://www.lintcode.com/problem/remove-node-in-binary-search-tree/description

Given a BST and a number v a l u e value requires that the node equal to the value be deleted in the BST, and the deleted root is returned.

The idea is to use recursion. If the root of the tree is not equal to v a l u e value , then recursively delete the left subtree or right subtree according to the size relationship with the root of the tree and connect it to root. Otherwise if the root of the tree is equal to v a l u e value , if one of the left and right subtrees is empty, then directly return the root of the non-empty subtree, otherwise the left and right subtrees are not empty, then we can overwrite the maximum value in the left subtree, root, Then delete the maximum value. Since the maximum value of the left subtree must be at the rightmost end of this subtree, and the right subtree of this node is empty, it is very convenient to delete. code show as below:

public class Solution {
    /*
     * @param root: The root of the binary search tree.
     * @param value: Remove the node with given value.
     * @return: The root of the binary search tree after removal.
     */
    public TreeNode removeNode(TreeNode root, int value) {
        // write your code here
        if (root == null) {
            return root;
        }
        
        if (root.val < value) {
            root.right = removeNode(root.right, value);
        } else if (root.val > value) {
            root.left = removeNode(root.left, value);
        } else {
            if (root.left == null) {
                return root.right;
            } else if (root.right == null) {
                return root.left;
            } else {
            	// 开两个节点,一个节点在前,另一个跟在后面
                TreeNode prev, cur;
                prev = cur = root.left;
                cur = cur.right;
                // 如果root的左子树的右子树已经为空了,那么直接把左子树的左子树连到root上即可;
                // 否则就删掉左子树的最右端的节点即可
                if (cur == null) {
                    root.val = prev.val;
                    root.left = prev.left;
                } else {
                    while (cur.right != null) {
                        cur = cur.right;
                        prev = prev.right;
                    }
                    root.val = cur.val;
                    prev.right = cur.left;
                }
            }
        }
        
        return root;
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

Space-time complexity O ( h ) O(h)

Published 387 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105465516