TRT
Sign in
mediumCoreLeetCode#search then attach#return the subtree root

Insert into a binary search tree

Insert a value into a binary search tree by searching for its empty spot and attaching a new leaf.

The Runtime Theory Team1 min read
Taught inInsert and deletePro — members onlyInserting into a binary search tree is a search that ends by attaching a node. Deleting is harder when the node has two children: its successor takes its place.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inroot = [4, 2, 7, 1, 3], val = 5

out[4, 2, 7, 1, 3, 5]

inroot = [40, 20, 60, 10, 30, 50, 70], val = 25

out[40, 20, 60, 10, 30, 50, 70, null, null, 25]

inroot = [], val = 5

out[5]

Given the root of a binary search tree and a value not already in it, insert the value and return the root of the tree.

Before you code

The new value goes exactly where a search for it would fall off the tree. Write it in the return-the-subtree-root style, and the empty tree needs no special case.

Hints

  1. insert(None, val) returns a new node.
  2. Otherwise recurse left or right and assign the result back to node.left or node.right, then return node.
  3. Iterative version: walk down remembering the parent, then attach the new node to the correct side of the parent.

Production & complexity notes

When solving Insert into a binary search tree on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Insert and delete to reinforce the underlying pattern.

What it practices

Insertion as a search plus one link, from Insert and delete.

Not started

Sign in to save your learning progress.

Sign in to save