InterviewPrepKit

Home / Coding / Trees

Delete Node in a BST

medium Original ↗
Solving tips
  • Split into two phases: use the BST property to descend to the node in O(h), then handle deletion by case.
  • Three cases: leaf returns None, one child returns that child, two children replace the value with the in-order successor (min of right subtree) then recursively delete that successor.
  • Always reattach the recursive result: root.left = self.deleteNode(root.left, key) — forgetting the assignment loses the spliced subtree, and returning root at the end handles deleting the actual root.
  • Pitfall: after copying succ.val into the node, recurse on the right subtree with succ.val (not the original key), and don't assume the successor is a leaf — it may have a right child. O(h) time and space.

Problem

You are given the root of a Binary Search Tree (BST) and a value key. Delete the node whose value equals key, if it exists, and return the root of the resulting tree. The tree must remain a valid BST after the deletion.

Recall the BST property: every left descendant is smaller than a node and every right descendant is larger. Deleting a node with two children requires replacing it with a value that preserves this ordering.

If key is not in the tree, return the tree unchanged.

Examples

Example 1

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

Node 3 has two children (2 and 4). Replace 3 with its in-order successor 4 (the smallest value larger than 3), then remove that successor from its old spot.

Example 2

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

There is no node with value 0, so the tree is returned unchanged.

Example 3

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

Node 6 has only a right child 7, so 6 is simply replaced by 7.

Constraints

  • The number of nodes is in the range [0, 10^4].
  • -10^5 <= Node.val <= 10^5
  • Each node has a unique value.
  • -10^5 <= key <= 10^5

Think about it first

Hint 1 Use the BST property to *find* the node in O(h): go left if key < node.val, right if key > node.val. The interesting part is what to do once you find it.
Hint 2 Three cases for the found node: no children (just remove it), one child (splice the child in), two children (the tricky case). Handle them separately.
Hint 3 For a node with two children, replace its value with its in-order successor — the smallest value in its right subtree — then recursively delete that successor from the right subtree. (The in-order predecessor, the largest value in the left subtree, works symmetrically.)
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.