Delete Node in a BST

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.

30:00

Delete Node in a BST
medium
Free written solution
Topics
Companies

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][0, 10^4].

  • −105≤Node.val≤105-10^5 \leq \text{Node.val} \leq 10^5

  • Each node has a unique value.

  • root is a valid binary search tree.

  • −105≤key≤105-10^5 \leq \text{key} \leq 10^5

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.

current call
search path
node to delete
in-order successor
moves up / relinked
Variables
VariableValue
rootnull
key3
DepthFunction Call
Stack empty
0/11