Delete Node in a BST - Problem

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

There are three cases to consider when deleting a node:

  • Node has no children (leaf node): Simply remove it
  • Node has one child: Replace the node with its child
  • Node has two children: Replace the node with its inorder successor (or predecessor)

Input & Output

Example 1 — Node with Two Children
$ Input: root = [5,3,6,2,4,null,7], key = 3
Output: [5,4,6,2,null,null,7]
💡 Note: Node 3 has two children (2 and 4). Replace it with inorder successor 4, then delete original 4.
Example 2 — Leaf Node
$ Input: root = [5,3,6,2,4,null,7], key = 2
Output: [5,3,6,null,4,null,7]
💡 Note: Node 2 is a leaf node (no children), so simply remove it from the tree.
Example 3 — Root Node Deletion
$ Input: root = [7], key = 7
Output: []
💡 Note: Deleting the only node in the tree results in an empty tree.

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • -105 ≤ Node.val ≤ 105
  • Each node has a unique value
  • -105 ≤ key ≤ 105

Visualization

Tap to expand
Delete Node in a BST INPUT Original BST: 5 3 key=3 6 2 4 successor 7 root = [5,3,6,2,4,null,7] key = 3 Delete node with value 3 Node 3 has TWO children ALGORITHM STEPS 1 Search for Key Compare key with node Go left if key < node 2 Found Node 3 Has two children (2, 4) Use successor method 3 Find Successor Inorder successor = 4 (smallest in right) 4 Replace and Delete Copy 4 to position of 3 Delete original 4 Three Deletion Cases: Leaf Just remove 1 Child Replace 2 Children Successor Current case: Two children Time: O(h), Space: O(h) FINAL RESULT Updated BST: 5 4 replaced 3 6 2 7 Output: [5,4,6,2,null,null,7] OK - BST Property Maintained Left subtree < root < right 2 < 4 < 5 < 6 < 7 Key Insight: When deleting a node with two children, replace it with its inorder successor (smallest value in right subtree) or predecessor (largest in left). This maintains BST property. The successor has at most one child (right), making its removal a simpler case. Time complexity is O(h) where h is tree height. TutorialsPoint - Delete Node in a BST | BST Property Search with Recursive Deletion
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
87.6K Views
High Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen