Community Problem

Insert into a Binary Search Tree

Difficulty: Medium

Insert a new value into a BST while preserving the ordering invariant; any valid resulting BST is accepted.

Insert into a Binary Search Tree

Insert a new value into a BST while preserving the ordering invariant; any valid resulting BST is accepted.

MEDIUM
Free
trees
bst
recursion
davidmorgan

By @davidmorgan

January 24, 2026

·

Updated May 18, 2026

624 views

16

4.2 (11)

I had to write this exact function from scratch when I was building a small ordered set for a CLI parser, and the recursion is so clean it doubles as a teaching moment for anyone who has only ever read about BSTs. The catalog covers Validate BST and Kth Smallest, but it skipped the constructive side: how do you actually grow a BST one node at a time?

Insert into a Binary Search Tree

Given the root of a binary search tree (BST) and an integer val to insert into the tree, return the root of the BST after the insertion. It is guaranteed that val does NOT already exist in the original BST.

Notice that there may exist multiple valid BSTs after the insertion. You may return any of them, as long as the resulting tree is a valid BST.

Examples

Example 1:

  • Input: root = [4, 2, 7, 1, 3], val = 5
  • Output: [4, 2, 7, 1, 3, 5]
  • Explanation: 5 > 4 so go right. 5 < 7 so go left. The left child of 7 is empty, so 5 becomes the left child.

Example 2:

  • Input: root = [40, 20, 60, 10, 30, 50, 70], val = 25
  • Output: [40, 20, 60, 10, 30, 50, 70, null, null, 25]
  • Explanation: 25 < 40, 25 > 20, 25 < 30. The left child of 30 is empty, so 25 becomes the left child.

Example 3:

  • Input: root = [], val = 5
  • Output: [5]
  • Explanation: An empty tree gets a single root node.

Example 4:

  • Input: root = [4, 2, 7, 1, 3], val = 6
  • Output: [4, 2, 7, 1, 3, 6]
  • Explanation: 6 > 4, 6 < 7. Insert as left child of 7.

Constraints

  • The number of nodes in the tree will be in the range [0, 10^4].
  • -10^8 <= Node.val <= 10^8.
  • All the values Node.val are unique.
  • -10^8 <= val <= 10^8.
  • val does not exist in the original BST.

Follow-up

Can you do it iteratively? When does the iterative version pay off (hint: stack frames matter for very tall trees)?

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems