Bird
Raised Fist0
Interview Prepbinary-search-treesmediumAmazonGoogleFacebook

Delete Node in a BST

Choose your preparation mode3 modes available
Steps
setup

Start at root node 5

Begin the deletion process at the root node with value 5. The key to delete is 3, which is less than 5, so we will search the left subtree.

💡 Starting at the root is essential to traverse the BST correctly to find the node to delete.
Line:if not root: return None if key < root.val:
💡 The BST property guides the search direction for the key.
📊
Delete Node in a BST - Watch the Algorithm Execute, Step by Step
Watching each recursive call and decision helps you understand how the BST properties are maintained during deletion.
Step 1/12
·Active fillAnswer cell
Current node: 1
536247
DFS Stack
1 (entered)key=3
Current node: 2
536247
DFS Stack
2 (entered)key=31 (left_done)key=3
Current node: 2
536247
DFS Stack
2 (entered)key=31 (left_done)key=3
Current node: 2
536247
DFS Stack
2 (entered)key=31 (left_done)key=3
Current node: 2
536247
DFS Stack
2 (entered)key=31 (left_done)key=3
Current node: 5
536247
DFS Stack
5 (entered)2 (entered)key=31 (left_done)key=3
Return: {"successor_node_id":5}
Current node: 2
546247
DFS Stack
2 (entered)key=31 (left_done)key=3
Current node: 5
546247
DFS Stack
5 (entered)key=42 (entered)key=31 (left_done)key=3
Current node: 5
546247
DFS Stack
5 (entered)key=42 (entered)key=31 (left_done)key=3
Current node: 2
546247
DFS Stack
2 (returning)key=31 (left_done)key=3
Current node: 1
54627
DFS Stack
1 (returning)key=3
54627
Return: [5,4,6,2,null,null,7]

Key Takeaways

The recursive search guided by BST properties efficiently locates the node to delete.

Without visualization, it's hard to see how recursion narrows down the search path.

Replacing a node with its inorder successor preserves BST order after deletion.

This insight is subtle in code but clear when watching the successor being found and replacing the node.

Deleting the successor node recursively handles the duplicate value cleanly.

The recursive deletion of the successor node is a key step that can be overlooked without step-by-step tracing.