Insert into a Binary Search Tree (LeetCode 701): Solution and Explanation

Medium
Tree
Binary Search Tree
Binary Tree

Given the root of a binary search tree and a value that is not in it, insert the value and return the root. The expected answer attaches the new node as a leaf.

Intuition

Imagine searching for val even though it is not in the tree. At every node the BST order tells you which way to go, and since the value is missing the search must end at an empty child.

That empty child is the right home for the new node. Everything on the path agreed that val belongs on that side, so putting a leaf there keeps every left subtree smaller and every right subtree larger.

Nothing else has to change. Other valid trees exist, for example ones that put val at the root and rearrange, but the leaf insert touches a single pointer and is what the tests expect.

Approach: Iterative leaf insert

  1. Create the new node. If root is null, return it.
  2. Set cur = root and loop.
  3. If val < cur.val: when cur.left is null, set cur.left = node and stop; otherwise move cur = cur.left.
  4. Otherwise do the same on the right side.
  5. Return root, which has not changed.

Step-by-step example

root = [4,2,7,1,3], val = 5
  1. At 4: 5 > 4, and 4.right is 7, so move to 7.
  2. At 7: 5 < 7, and 7.left is empty.
  3. Attach 5 as the left child of 7.
  4. Return root 4. Serialized: [4,2,7,1,3,5].

Code: Python, Java, C++

1class Solution:
2    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
3        node = TreeNode(val)
4        if not root:
5            return node
6        cur = root
7        while True:
8            if val < cur.val:
9                if not cur.left:
10                    cur.left = node
11                    break
12                cur = cur.left
13            else:
14                if not cur.right:
15                    cur.right = node
16                    break
17                cur = cur.right
18        return root
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(h)

The walk goes down one level per step, so it takes at most h + 1 comparisons where h is the tree height: O(log n) when balanced, O(n) for a chain.

Space

O(1)

Only the cur pointer and the new node are kept. The recursive version uses O(h) stack instead.

Other approaches

Recursive insert (time O(h), space O(h))

If root is null return a new node; otherwise assign root.left = insert(root.left, val) or root.right = insert(root.right, val) and return root. Shorter, gives the same tree.

Rebuild a balanced tree (time O(n), space O(n))

Collect values in order, insert val, and build a balanced BST. Valid as a BST but a different tree, slower, and not what the tests expect.

Common mistakes

  • Forgetting the empty tree. With no root there is nothing to walk, so return the new node directly.
  • Moving to the child before checking it is null, which loses the parent you needed to attach to.
  • Returning the new node instead of the original root when the tree was not empty.

Frequently asked questions

Why does a leaf insert always keep the BST valid?

Every comparison on the way down put val on the same side as the branch taken. The new leaf therefore lies inside every range those ancestors define.

Is the result unique?

No, many BSTs hold the same values. LeetCode accepts any valid one, but here the tests expect the leaf insert, which is also the simplest.

Does the tree stay balanced?

Not necessarily. Inserting sorted values one after another builds a chain. Self-balancing trees such as AVL or red-black trees add rotations to fix that.