#701

Insert into a Binary Search Tree

Medium BST walk to a null slot

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

?The problem

Insert a new value (not already present) into a BST and return the root.

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

◎Understanding

Really asking: add a new value in the right place.

Why this works: walk down as if searching; the empty spot where you fall off is where the new node goes.

Example: insert 5 into 4 (2, 7)

5 > 4 → right 7, 5 < 7 → left is empty → place 5

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting to return a new node for an empty tree.

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