← Questions

Delete a node from a binary search tree

0
GoogleCodingLast asked Apr 2025

A coding interview question asked in Google's onsite coding round, last asked Apr 2025. It tests trees and binary search tree.

Given the root of a binary search tree with unique values and a key, delete the node holding the key if it exists and return the root of the resulting tree, which must still be a valid BST. The node may be a leaf, have one child, have two children, or be the root.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • class TreeNode: val: int; left, right: TreeNode | None
  • delete_node(root: TreeNode | None, key: int) -> TreeNode | None — returns the original root unchanged if the key is missing. For a node with two children, replace it with its in-order successor.

Example

        5
       / \
      3   6
     / \   \
    2   4   7

delete_node(root, 3)     # two children: 4 (the successor) takes 3's place
        5
       / \
      4   6
     /     \
    2       7

delete_node(root, 5)     # the root: 6 takes its place and 7 moves up under 6
        6
       / \
      3   7
     / \
    2   4

delete_node(root, 7)     # a leaf: just removed
delete_node(root, 9)     # missing: the tree is unchanged

Constraints

  • Up to 10^4 nodes; the tree may be skewed. Aim for O(h) time, where h is the height.

Clarifying questions

  • Are values unique? If not, where do duplicates go?
  • Successor or predecessor for the two-child case, or either?
  • Should the function mutate the tree or build a new one?
  • Is the tree balanced, or can it be a long chain?

What a strong answer covers

  • Search down by comparison; no full traversal.
  • The three cases: a leaf is removed; a node with one child is replaced by that child; a node with two children takes the value of the smallest node in its right subtree, which is then deleted from that subtree (it has at most one child).
  • Returning the new subtree root at each level so the root itself can change.
  • O(h) time; O(h) stack for the recursive version or O(1) iteratively, with parent pointers tracked.
  • Tests: delete the root, a leaf, a one-child node, a two-child node whose successor has a right child, a missing key, the only node.

Follow-ups

  • Write it iteratively.
  • How does deletion work in an AVL or red-black tree, and what extra work keeps it balanced?
  • Duplicates are allowed (stored in the right subtree, or as a count per node).

Where it's asked

  • Google · Onsite coding · Last asked Apr 202545 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)

What it tests

trees · binary search tree

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding