Problem · Tree
Delete Node in a BST
Learn this problemProblem statement
You are given the root of a binary search tree and an integer key. Delete the node whose value equals key, if it exists, and return the updated root.
The returned tree must remain a binary search tree. When the deleted node has two children, replace its value with the smallest value in its right subtree, then delete that successor node. This deterministic canonical strategy fixes one serialized output for the runner.
Function
deleteNode(root: TreeNode, key: int) → TreeNodeExamples
Example 1
root = [5,3,6,2,4,null,7]key = 3return = [5,4,6,2,null,null,7]Node 3 has two children. Its inorder successor is 4, which takes its place.
Example 2
root = [5,3,6,2,4,null,7]key = 0return = [5,3,6,2,4,null,7]The key is absent, so the tree is unchanged.
Example 3
root = []key = 0return = []An empty tree remains empty.
Constraints
- The tree contains between
0and10000nodes. -100000 <= Node.val <= 100000.- Every node value is unique and the input is a valid binary search tree.
-100000 <= key <= 100000.