Skip to content

Delete Node in a BST

MediumTrees
Decode it first. Clues, constraints, pattern and plan before any code.

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.

root = [5, 3, 6, 2, 4, null, 7], key = 3  →  [5, 4, 6, 2, null, null, 7]   (or [5, 2, 6, null, 4, null, 7])
root = [5, 3, 6, 2, 4, null, 7], key = 0  →  unchanged
root = [],                       key = 0  →  []

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