#450

Delete Node in a BST

Medium Three deletion cases

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Delete the node with a given key from a BST and return the new root.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: remove a value and keep it a BST.

Why this works: a leaf or one-child node is replaced by its child. A two-child node takes the smallest value from its right subtree, which is then deleted there.

Example: delete 3 from 5 (3 (2, 4), 6)

3 has two children → successor 4copy 4 into the node, delete the old 4 → 5 (4 (2), 6)

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Copying the successor's value but forgetting to delete the successor node, leaving a duplicate.

Solve on LeetCode ↗
Complexity
  • Time: O(h).
  • Space: O(h).
Topic: Binary Search Trees
🎬 Episodes 61–63: video coming soon