Delete Node in a BST

medium

Given the root of a binary search tree and a key, delete the node with that value (if present) and return the root of the updated BST, keeping it a valid BST.

The tree is given/returned in level-order (breadth-first), using null for missing children.

Hints

Deletion is search plus three cases at the found node.
Zero or one child: splice the node out by returning its (only) child.
Two children: replace the value with the inorder successor (min of the right subtree), then delete that successor.

Common doubts

It's the smallest value larger than the node, so it can sit in the node's place without breaking the ordering — and you could symmetrically use the predecessor (max of the left subtree).
The successor is the leftmost node of the right subtree, so it has no left child — a 0/1-child splice.
The search falls off the tree and you return it unchanged.

Interview follow-ups

Yes — the largest value in the left subtree also preserves the invariant; the resulting tree just differs slightly.
Same three cases, then rotations/recoloring on the way up to restore balance (AVL/red-black).

Fun facts

  • Repeated deletions using only the successor can gradually skew a tree left — some implementations alternate successor/predecessor to keep it balanced.
  • The two-child case is the only tree operation where you copy a value rather than move a pointer.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [5, 3, 6, 2, 4, null, 7], key = 3
Output: [5, 4, 6, 2, null, null, 7]
3 has two children; it's replaced by its inorder successor 4.
Example 2
Input: root = [5, 3, 6, 2, 4, null, 7], key = 0
Output: [5, 3, 6, 2, 4, null, 7]
0 is not in the tree; nothing changes.
Constraints

- The number of nodes is in the range [0, 10^4] - -10^5 <= Node.val <= 10^5 - root is a valid BST - -10^5 <= key <= 10^5

Solve this problem →