Insert into a Binary Search Tree

medium

Given the root of a binary search tree and a value val to insert, insert it and return the root of the (still valid) BST. The value is guaranteed not to already exist. Any valid BST resulting from the insertion is accepted, but a natural insert always creates a new leaf.

The tree is given/returned in level-order (breadth-first), using null for missing children.

Hints

Insertion is search that doesn't stop early.
Walk down as if searching for val; you'll reach a null child.
That null slot is exactly where val belongs — attach a new leaf.

Common doubts

Following the comparisons keeps the ordering; the null pointer you reach is the only place val fits without violating the invariant.
No — a plain BST insert only adds a new leaf; rebalancing is a separate concern (AVL/red-black).
The new value becomes the root.

Interview follow-ups

Insert the leaf the same way, then rotate on the way back up to restore the height invariant (AVL) or color rules (red-black).
Find it, then handle 0/1/2 children — replacing a two-child node with its inorder successor.

Fun facts

  • The sequence of BST inserts determines the tree's shape — the same values in a different order give a different (possibly skewed) tree.
  • Inserting sorted values one by one produces a completely degenerate (linked-list) BST.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: root = [4, 2, 7, 1, 3], val = 5
Output: [4, 2, 7, 1, 3, 5]
5 is inserted as the left child of 7.
Example 2
Input: root = [], val = 5
Output: [5]
Into an empty tree, the value becomes the root.
Constraints

- The number of nodes is in the range [0, 10^4] - -10^8 <= Node.val <= 10^8 - root is a valid BST - val does not exist in the original BST

Solve this problem →