Skip to content
Decoder

Delete Node in a BST

Medium

Problem

Given the root of a binary search tree and a value key, remove the node holding key (if there is one) and return the root of the resulting tree. The result must still be a valid BST holding every other value.

There is more than one valid way to rebuild the tree after a removal. Any valid BST with the right values is accepted: the tests check the BST property and the in-order contents, not one exact shape.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
root = [5, 3, 6, 2, 4, null, 7], key = 3
Output
[5, 4, 6, 2, null, null, 7]
Why
or [5, 2, 6, null, 4, null, 7]

Example 2

Input
root = [5, 3, 6, 2, 4, null, 7], key = 0
Output
unchanged

Example 3

Input
root = [], key = 0
Output
[]

Constraints

  • 0 <= number of nodes <= 10^4
  • -10^5 <= Node.val <= 10^5
  • All values are unique and root is a valid BST.
  • -10^5 <= key <= 10^5

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.