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:
- Search for the node containing the key
- 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code