Skip to content
Problem 701 · LeetCode 701(opens in a new tab)

Insert into a Binary Search Tree

MediumBinary search trees

You are given the root of a binary search tree (for every node, smaller values are in its left subtree and larger values in its right subtree) and a number val that is not in the tree yet.

Add a node with value val so the tree is still a binary search tree, and return the root. Several shapes can be valid; here the new node is always added as a leaf, at the empty spot you reach by walking down from the root.

Example 1

Input:  root = [8, 4, 12, 2, 6], val = 5
Output: [8, 4, 12, 2, 6, null, null, null, null, 5]
Why:    5 < 8, 5 > 4, 5 < 6: it becomes the left child of 6
2 more examples and the constraints

Example 2

Input:  root = [], val = 3
Output: [3]
Why:    an empty tree gets the new node as its root

Example 3

Input:  root = [10, 5, 15], val = 20
Output: [10, 5, 15, null, null, null, 20]
Why:    20 is the largest, so it goes right, right

Constraints

  • 0 ≤ number of nodes ≤ 10,000
  • −100,000,000 ≤ each value, val ≤ 100,000,000
  • All values are different, and val is not in the tree

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. RecursionO(h)
  2. Walk down with a loopO(h)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
RecursionO(h)
Short; uses stack per level
Walk down with a loopO(h)
Best; no call stack

h = height of the tree: up to n for a tree in a line, about log n when balanced.

Edge cases to test

  • Empty tree. Return the new node; it is the whole tree.
  • New smallest or largest value. The walk goes left (or right) every time and ends below the outermost node.
  • Tree in a line. 10,000 nodes all on one side: the walk is 10,000 steps long, and recursion is 10,000 calls deep.
  • Gap deep inside. With 20, 10, 15 on the path, 17 ends up as the right child of 15, far from the root.

Common mistakes

  • Returning the new node instead of the root when the tree was not empty.
  • Forgetting the empty tree, so the code reads root.val on nothing.
  • Rebuilding or rebalancing the tree; no existing node needs to move.

How to talk through it

  1. 1Clarify. Can the tree be empty? Is val surely not in it? Any valid tree is fine, so a new leaf is enough.
  2. 2Use the order. Each comparison says which subtree val belongs in, like a search.
  3. 3Give the recursion. Empty spot returns a new node; otherwise insert into one side and return root.
  4. 4Turn it into a loop. Only one path is walked, so one pointer replaces the call stack.
  5. 5Test out loud. Run the empty tree, a new smallest value and a tree in a line.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?