Delete with the predecessor instead
Challenge · Write code · about 15 min
Delete the node with key key from the BST with the given root and return the root of the result. If key is not in the tree, return the tree unchanged.
When the node has two children, copy the key of its in-order predecessor (the largest key in its left subtree) into it, then delete the predecessor from the left subtree. The tests expect exactly this shape.
Example 1
Input:
[[5,3,6,2,4,null,7],3]
Output:
[5,2,6,null,4,null,7]
3 has two children. Its predecessor 2 moves up.
Example 2
Input:
[[5,3,6,2,4,null,7],0]
Output:
[5,3,6,2,4,null,7]
0 is not in the tree.
Constraints
- 0 ≤ number of nodes ≤ 1,000
- Keys are distinct integers with 0 ≤ key ≤ 1,000
- The tree is a valid BST, given in level order; null marks a missing child
Learn the idea first: BST delete; successor and predecessor, a visual lesson.
More BST delete; successor and predecessor problems
- Pick the tree after a delete Warm-up
- Delete a node with two children Standard
- Implement delete Standard
- Successor Standard
- Spot the bug: lost subtree Standard