InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Delete Node in a BST

medium Original ↗ 00:00

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 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 work is in what to do once you find it.
Hint 2 Three cases for the found node: no children (remove it), one child (splice the child in), two children. 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.)

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug