Delete Node in a BST - Problem

You are given the root of a Binary Search Tree (BST) and a key value to delete. Your task is to remove the node with the given key while maintaining the BST property.

The deletion process involves two main phases:

  1. Search for the node containing the key
  2. Delete the node if found, ensuring the tree remains a valid BST

Return the root of the modified BST. Note that the root itself might change if it's the node being deleted.

BST Property: For any node, all values in the left subtree are smaller, and all values in the right subtree are larger than the node's value.

Input & Output

example_1.py โ€” Delete leaf node
$ Input: root = [5,3,6,2,4,null,7], key = 4
โ€บ Output: [5,3,6,2,null,null,7]
๐Ÿ’ก Note: Node 4 is a leaf node (no children), so we simply remove it. The tree structure remains unchanged except for the deleted node.
example_2.py โ€” Delete node with one child
$ 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). We replace it with its inorder successor, which is 4. Then we delete the original position of 4.
example_3.py โ€” Delete root node
$ Input: root = [5,3,6,2,4,null,7], key = 5
โ€บ Output: [6,3,7,2,4]
๐Ÿ’ก Note: Root node 5 has two children. We replace it with its inorder successor (6), then delete the original position of 6 in the right subtree.

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • -105 โ‰ค Node.val โ‰ค 105
  • Each node value is unique
  • root is a valid binary search tree
  • -105 โ‰ค key โ‰ค 105

Visualization

Tap to expand
๐Ÿ“š The Librarian's BST Deletion StrategyPerfectly Organized Digital LibraryID:3DataID:5DELETEID:7WebID:8Next!ID:12AIREMOVESuccessor takes placeSmart Librarian Rules:1. ๐Ÿ“– Isolated book? Just remove2. ๐Ÿ‘ฅ One dependent? Promote it3. ๐Ÿ‘ฅ๐Ÿ‘ฅ Two dependents? Find next in sequence to fill the gap!Tree Structure:5378
Understanding the Visualization
1
Locate the Book
Use the ordering system to quickly find the book to remove
2
Assess the Situation
Check if other books depend on this book's position
3
Smart Replacement
If needed, find the next book in sequence to fill the gap
Key Takeaway
๐ŸŽฏ Key Insight: Like a skilled librarian, the optimal BST deletion algorithm knows exactly how to maintain order with minimal disruption by using the inorder successor as a smart replacement strategy.
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
52.3K Views
High Frequency
~18 min Avg. Time
1.8K 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