450. Delete Node in a BST

Description

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:

  1. Search for a node to remove.

  2. 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

Tags

Tree

Solution

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.

Complexity

  • Time complexity: O(log(n))O(\log(n)), log(n)=H\log(n)=H when the tree is a balance one;

  • Space complexity: O(H)O(H)

Code

Reference

Last updated

Was this helpful?