450. Delete Node in a BST
Last updated
Was this helpful?
Last updated
Was this helpful?
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Follow up: Can you solve it with time complexity O(height of tree)
?
Example 1:
Constraints:
The number of nodes in the tree is in the range [0, 104]
.
-105 <= Node.val <= 105
Each node has a unique value.
root
is a valid binary search tree.
-105 <= key <= 105
Tree
Return null when root is null. We find the target node first, then check if it matches the following scenario:
The target is a leaf, then return null;
The target only has one child, then return that child node;
The target has both left and right children. We first find the smallest (leftmost) node of the right sub-tree overwrite the key (root's value) with successor's value. The next step is to delete the new key - successor's value from the sub-tree whose root is the successor, and assign the processed tree root to the ancestor's child.
Time complexity: , when the tree is a balance one;
Space complexity:
****删除二叉搜索树中的节点