Given the root of a binary search tree and a value `key`, delete the node holding `key` (if there is one) and return the root of the updated BST.
Deletion has two stages: search for the node, then remove it. A node with at most one child is replaced by that child. A node with two children takes the value of its **in-order successor** (the smallest value in its right subtree), and that successor is then deleted from the right subtree. Several valid trees can result from a deletion, and any valid BST with the right values is accepted. The walkthrough uses the in-order successor.
Given the root of a binary search tree and a value key, delete the node holding key (if there is one) and return the root of the updated BST.
Deletion has two stages: search for the node, then remove it. A node with at most one child is replaced by that child. A node with two children takes the value of its in-order successor (the smallest value in its right subtree), and that successor is then deleted from the right subtree. Several valid trees can result from a deletion, and any valid BST with the right values is accepted. The walkthrough uses the in-order successor.
Example 1:
Input: {"root":[5,3,6,2,4,null,7],"key":3}
Output: [5,4,6,2,null,null,7]
Constraints:
The number of nodes in the tree is in the range [0,104].
−105≤Node.val≤105
Each node has a unique value.
root is a valid binary search tree.
−105≤key≤105
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"root":[5,3,6,2,4,null,7],"key":3}
Delete 3. Use the BST order to search: smaller keys go left, larger keys go right.
key = 3
calls:
-
536247
Left to right the nodes stay in sorted order, before and after the delete.