Magicsheet logo

Insert into a Binary Search Tree

Medium
25%
Updated 8/1/2025

Insert into a Binary Search Tree

1. What is this problem about?

The Insert into a Binary Search Tree interview question asks you to add a new value to an existing BST while maintaining the BST property (left child < parent < right child). You are guaranteed that the new value does not already exist in the tree. There are often multiple valid ways to insert, but the simplest is to add it as a new leaf.

2. Why is this asked in interviews?

Companies like Microsoft and Google use the Insert into a BST coding problem to evaluate basic recursive thinking and understanding of tree invariants. It’s a core Binary Tree interview pattern that checks if you can navigate a hierarchy based on value comparisons.

3. Algorithmic pattern used

This problem uses Recursive Search and Placement.

  1. Compare: If val < root.val, move to the left subtree.
  2. Base Case: If the left child is null, insert the new node there.
  3. Recurse: Repeat for the right side if val > root.val.
  4. Return: The function typically returns the root of the modified subtree.

4. Example explanation

BST: 4 is root, 2 is left, 7 is right. Insert 5.

  1. 5>45 > 4: Go right.
  2. At 7, 5<75 < 7: Go left.
  3. Left of 7 is null. Insert 5 here. Result: 4 -> {2, 7}, 7 -> {5, null}.

5. Common mistakes candidates make

  • Breaking BST property: Attempting to insert in the middle of the tree, which requires complex rotations. Inserting at a leaf is always easier.
  • Not updating parent: In the recursive approach, failing to assign the result of the recursive call back to root.left or root.right.
  • Handling root: Not returning the new node if the original tree was empty.

6. Interview preparation tip

Practice both recursive and iterative versions of this. The iterative version uses a while loop and a trailing parent pointer, which is a great way to demonstrate memory management skills without using the recursion stack.

Similar Questions