AlgoFrames

Implement delete

Standard · Write code · about 12 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 successor (the smallest key in its right subtree) into it, then delete the successor from the right subtree. The tests expect exactly this shape.

Example 1

Input:

[[5,3,6,2,4,null,7],3]

Output:

[5,4,6,2,null,null,7]

3 has two children. Its successor 4 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