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 BST: Input → Process → Output536247Input: Delete key = 3Deletion Cases:• No children: Remove• Two children: Replacewith inorder successor54627Output: Node 3 replaced by 4BST property maintained: left < node < right
Understanding the Visualization
1
Input BST
Binary Search Tree with target key to delete
2
Search & Delete
Find node using BST property and apply deletion rules
3
Output BST
Resulting BST after deletion with structure preserved
Key Takeaway
🎯 Key Insight: Use BST property for O(log n) search and replace nodes with two children using their inorder successor
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