Delete Node in a BST
Problem
Given the root of a binary search tree and a key, delete the node with the given key in the BST and return the root of the modified tree. You may assume the BST property must be maintained after deletion.
- The number of nodes in the tree is in the range [0, 10⁴]
- −10⁵ ≤ Node.val ≤ 10⁵
- Each node has a unique value
- root is a valid binary search tree
- −10⁵ ≤ key ≤ 10⁵
Example
root = [5,3,6,2,4,null,7], key = 3[5,4,6,2,null,null,7]The node with value 3 is found. It has two children, so it is replaced by its in-order successor, which is 4. The successor node is then deleted from its original position. The resulting tree maintains the BST property.
Approach
Straightforward Solution
A brute-force approach might search for the node, then restructure the tree without careful handling of the BST property, potentially breaking the tree. Alternatively, one might try to rebuild the tree from scratch after deletion, which is inefficient.
Core Observation
In a BST, the left subtree contains values less than the node, and the right subtree contains values greater. Deleting a node requires preserving this property. When deleting a node with two children, replacing it with its in-order successor (the smallest node in the right subtree) maintains the BST structure.
Path to Optimal
The key insight is to use recursion to locate the node to delete. If the node has zero or one child, deletion is straightforward by returning the child or None. If the node has two children, find the in-order successor by traversing to the leftmost node in the right subtree, replace the node's value with the successor's value, then recursively delete the successor node. This approach preserves the BST property and ensures all subtrees remain valid BSTs.
Optimal Approach
Use a recursive DFS approach. At each node, compare the key with the node's value to decide whether to recurse left or right. Upon finding the node to delete, handle three cases: no children (return None), one child (return that child), or two children (replace with in-order successor and delete successor recursively). This guarantees O(h) time complexity, where h is the tree height.
Time
O(h)
The algorithm traverses from the root down to the node to delete, which takes O(h) time, where h is the height of the BST. Finding the in-order successor and deleting it also takes O(h) in the worst case.
Space
O(h)
The recursion stack consumes O(h) space due to the depth of the tree. No additional data structures are used.
Pattern Spotlight
DFS (Recursive State Exploration in BST)
When modifying a BST, use recursion to navigate and update subtrees, handling deletion by carefully replacing nodes with their in-order successor or predecessor to maintain BST invariants.
Solution
| 1 | class Solution: |
| 2 | def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: |
| 3 | if not root: |
| 4 | return None |
| 5 | |
| 6 | if key < root.val: |
| 7 | root.left = self.deleteNode(root.left, key) |
| 8 | |
| 9 | elif key > root.val: |
| 10 | root.right = self.deleteNode(root.right, key) |
| 11 | |
| 12 | else: |
| 13 | if not root.left: |
| 14 | return root.right |
| 15 | |
| 16 | if not root.right: |
| 17 | return root.left |
| 18 | |
| 19 | successor = root.right |
| 20 | |
| 21 | while successor.left: |
| 22 | successor = successor.left |
| 23 | |
| 24 | root.val = successor.val |
| 25 | root.right = self.deleteNode(root.right, successor.val) |
| 26 | |
| 27 | return root |
Step-by-Step Solution
Recursively Locate the Node to Delete
| 3 | if not root: |
| 4 | return None |
| 6 | if key < root.val: |
| 7 | root.left = self.deleteNode(root.left, key) |
| 9 | elif key > root.val: |
| 10 | root.right = self.deleteNode(root.right, key) |
Objective
To traverse the BST recursively to find the node with the given key, directing the search left or right based on BST ordering.
Key Insight
The BST property allows pruning the search space: if the key is less than the current node's value, the node must be in the left subtree; if greater, in the right subtree. This reduces the search from O(n) to O(h), where h is the tree height. Recursion naturally handles subtree updates by returning the modified subtree root.
Interview Quick-Check
Core Logic
Use BST ordering to decide whether to recurse left or right, ensuring efficient search for the node to delete.
State & Boundaries
Return None immediately if the current node is None, indicating the key is not found in this path.
Common Pitfalls & Bugs
Failing to assign the recursive call's result back to root.left or root.right can cause the tree structure to remain unchanged after deletion.
Handle Deletion of Node with Zero or One Child
| 12 | else: |
| 13 | if not root.left: |
| 14 | return root.right |
| 16 | if not root.right: |
| 17 | return root.left |
Objective
To delete the node when it has at most one child by returning the non-null child or None, effectively removing the node.
Key Insight
If the node has no left child, its right child (which may be None) replaces it. Similarly, if it has no right child, its left child replaces it. This direct replacement maintains the BST property without further restructuring. This case is simpler than the two-child case and serves as a base for the recursive deletion.
Interview Quick-Check
Core Logic
Return the non-null child to replace the deleted node, preserving BST structure.
State & Boundaries
Check for absence of left or right child separately to handle all zero or one child cases.
Common Pitfalls & Bugs
Not returning the correct child or forgetting to return at this stage can cause incorrect tree structure or infinite recursion.
Replace Node with In-Order Successor and Delete Successor
| 19 | successor = root.right |
| 21 | while successor.left: |
| 22 | successor = successor.left |
| 24 | root.val = successor.val |
| 25 | root.right = self.deleteNode(root.right, successor.val) |
Objective
To replace the node's value with its in-order successor's value and recursively delete the successor node from the right subtree.
Key Insight
The in-order successor is the smallest node in the right subtree, found by traversing left until no further left child exists. Replacing the node's value with the successor's value preserves BST ordering. Then, the successor node is deleted recursively from the right subtree to avoid duplicates. This two-step process ensures the BST remains valid after deletion.
Interview Quick-Check
Core Logic
Find the leftmost node in the right subtree as the in-order successor, replace the current node's value, then delete the successor recursively.
State & Boundaries
Use a while loop to find the successor, ensuring the smallest value greater than the current node.
Common Pitfalls & Bugs
Failing to delete the successor node after replacement leads to duplicate values in the BST.
Return the Updated Root After Deletion
| 27 | return root |
Objective
To return the root of the updated subtree after deletion, allowing recursive calls to reconstruct the BST correctly.
Key Insight
Each recursive call returns the root of the modified subtree, which is assigned back to the parent's left or right pointer. This ensures that changes propagate up the recursion stack, maintaining the overall BST structure. Returning the root at the end of the function completes the recursive update.
Interview Quick-Check
Core Logic
Return the updated root to link the modified subtree back to its parent.
State & Boundaries
Ensure the return happens after all deletion logic to propagate changes correctly.
Line Analysis
This solution has 8 Critical lines interviewers watch for.
else:
Identify the node to delete (key equals current node's value).
This condition triggers the deletion logic, distinguishing the node to remove from other nodes.
while successor.left:
Traverse left to find the in-order successor (smallest node in right subtree).
Moving left until no further left child ensures the successor is the smallest node greater than the current node, preserving BST ordering.
root.right = self.deleteNode(root.right, successor.val)
Recursively delete the successor node from the right subtree.
Deleting the successor node removes the duplicate and maintains BST integrity, completing the replacement process.
root.left = self.deleteNode(root.left, key)
Recursively delete the key in the left subtree and update the left child.
Assigning the recursive call's result to root.left ensures the subtree is updated correctly after deletion.
root.right = self.deleteNode(root.right, key)
Recursively delete the key in the right subtree and update the right child.
Assigning the recursive call's result to root.right ensures the subtree is updated correctly after deletion.
return root.right
Return the right child to replace the current node.
Returning the right child effectively deletes the current node and reconnects the subtree correctly.
return root.left
Return the left child to replace the current node.
Returning the left child effectively deletes the current node and reconnects the subtree correctly.
root.val = successor.val
Replace the current node's value with the successor's value.
Copying the successor's value into the current node maintains BST property while preparing to delete the duplicate successor node.
if not root:
Check if the current node is None, indicating the key is not found in this path.
This base case terminates recursion when the search reaches a leaf's child, ensuring the function returns None to signal no deletion occurred here.
if key < root.val:
Check if the key is less than the current node's value to recurse left.
BST property guarantees that if the key is smaller, the node to delete must be in the left subtree, enabling efficient pruning.
elif key > root.val:
Check if the key is greater than the current node's value to recurse right.
BST property guarantees that if the key is larger, the node to delete must be in the right subtree, enabling efficient pruning.
if not root.left:
Check if the node has no left child.
If no left child exists, the right child (or None) replaces the node, preserving BST structure.
if not root.right:
Check if the node has no right child.
If no right child exists, the left child replaces the node, preserving BST structure.
successor = successor.left
Update successor to its left child during traversal.
This step moves the pointer down the left chain to find the minimal successor node.
return root
Return the updated root after deletion.
Returning the root allows recursive calls to reconstruct the BST correctly after modifications.
return None
Return None when the current node is null.
Returning None correctly signals to the parent call that this subtree is empty, maintaining tree integrity.
successor = root.right
Initialize the successor as the right child of the node to delete.
The successor is the candidate for replacement, starting at the right subtree root.
Test Your Understanding
Why is the in-order successor used to replace a node with two children during deletion in a BST?
Because the in-order successor is the smallest node in the right subtree, replacing the node with it preserves the BST property by ensuring all left subtree values remain smaller and all right subtree values remain larger.
Related Problems
DFS pattern
Don't just read it. Drill it.
Reconstruct Delete Node in a BST from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Delete Node in a BST drill