Trees · Binary Search Tree Operations

BST Search and Insert

Locating (or creating) a value's correct position in a BST by comparing it against the current node and moving to the left or right child accordingly - the single "compare and pick a side" primitive that both a pure lookup and an insert are built from.

  • 7 min read
  • 10 practice questions
  • 2 graded problems
On this page
  1. Description
  2. The approach
  3. A second flavor: iterative insert
  4. Where you'll see it
  5. Which tool for which job?
  6. Common mistakes
  7. Check yourself
  8. Key takeaways
  9. Quick revise
  10. Practice

Description

A binary search tree keeps one rule at every node: smaller keys to the left, larger to the right. That rule turns search into a single walk from the root, because each comparison throws away a whole subtree. Insert is the same walk, adding a node where the search falls off. This skill makes both automatic, and shows why the tree's shape, not its size, decides how fast they are.

We'll go from simple to more technical:

  1. The pattern: one compare-and-pick-a-side walk for search and insert.
  2. A second flavor: iterative insert with a parent pointer.
  3. Where ordered trees run in production (sorted maps, database indexes).
  4. What breaks it: sorted input, duplicate keys and a dropped return value.

The approach

In a BST, comparing with one node tells you which side the value must be on. So search walks one path: left if the value is smaller, right if it's larger. Insert walks the same path, and when it falls off the tree, the new node goes exactly there.

Inserting 6 into the tree 8 / 4, 12 / 2, 7:

At6 compared with itGo
8smallerleft
4largerright
7smallerleft: that spot is empty, so 6 goes there

left

8

4

12

2

7

6

left

8

4

12

2

7

6

Java

boolean searchBST(TreeNode root, int val) {
    TreeNode cur = root;
    while (cur != null) {
        if (cur.val == val) return true;
        cur = (val < cur.val) ? cur.left : cur.right;   // the other side can't contain val
    }
    return false;
}

TreeNode insert(TreeNode node, int val) {
    if (node == null) return new TreeNode(val);       // fell off the tree - this is where val belongs
    if (val < node.val) node.left = insert(node.left, val);
    else if (val > node.val) node.right = insert(node.right, val);
    return node;                                      // an equal key is ignored: this BST is a set
}

Python

def search_bst(root: TreeNode | None, val: int) -> bool:
    cur = root
    while cur is not None:
        if cur.val == val:
            return True
        cur = cur.left if val < cur.val else cur.right   # the other side can't contain val
    return False


def insert(node: TreeNode | None, val: int) -> TreeNode:
    if node is None:
        return TreeNode(val)                 # fell off the tree - this is where val belongs
    if val < node.val:
        node.left = insert(node.left, val)
    elif val > node.val:
        node.right = insert(node.right, val)
    return node                              # an equal key is ignored: this BST is a set

The assignment node.left = insert(...) is what links the new node to its parent on the way back up. Each step discards a whole subtree, so both operations cost O(height).

A second flavor: iterative insert

The recursive insert keeps O(height) stack frames just to relink the path on the way back. The iterative version only remembers the last node it passed, parent, and which side it fell off:

Java

TreeNode insertIterative(TreeNode root, int val) {
    TreeNode node = new TreeNode(val);
    if (root == null) return node;                     // empty tree: the new node is the root
    TreeNode parent = null, cur = root;
    while (cur != null) {
        if (val == cur.val) return root;               // already present
        parent = cur;
        cur = (val < cur.val) ? cur.left : cur.right;
    }
    if (val < parent.val) parent.left = node; else parent.right = node;
    return root;
}

Python

def insert_iterative(root: TreeNode | None, val: int) -> TreeNode:
    node = TreeNode(val)
    if root is None:
        return node                          # empty tree: the new node is the root
    parent, cur = None, root
    while cur is not None:
        if val == cur.val:
            return root                      # already present
        parent = cur
        cur = cur.left if val < cur.val else cur.right
    if val < parent.val:
        parent.left = node
    else:
        parent.right = node
    return root

Same O(height) time, O(1) extra space. Once cur is null, parent is the only way back to the node that needs the new child.

Where you'll see it

Java's TreeMap is a balanced BST (a red-black tree), and database indexes use B-trees, a wider relative. Both cost time in proportion to the tree's height, not its size. Python's standard library has no tree-based sorted map; the sortedcontainers package is the usual stand-in.

Which tool for which job?

You needUse
Find a key in a BSTone walk: go left if smaller, right if larger
Add a keythe same walk; attach a node where it falls off
Insert without O(h) stackthe iterative insert with a parent pointer
All keys known up frontsort them and build a balanced tree from the middle
O(log n) whatever the insertion ordera balanced tree: TreeMap / TreeSet, sortedcontainers in Python
Only membership, no ordera hash set - O(1) average

Common mistakes

MistakeWhat happensDo this instead
Inserting sorted keys into a plain BSTa chain of height n; every operation is O(n)shuffle, build from the sorted array, or use a balanced tree
No single rule for equal keysa search walks past a copy on the other sideignore, count in the node, or always one side
insert(node.left, val) without assigningthe new node is created and lostnode.left = insert(node.left, val) and root = insert(root, val)
Losing parent in the iterative insertnowhere to attach the new noderemember the last node and the side you fell off
Quoting O(log n) for any BSTwrong on skewed treessay O(h): log n balanced, n worst case

Check yourself

Try to answer before opening each one - recalling beats re-reading.

1. Keys 1, 2, 3, 4, 5 are inserted in that order into an empty BST. What shape is the tree, and what does a search cost?

Show answer

A chain: 1 at the root, 2 as its right child, 3 as 2's right child, and so on. Each key is larger than all before it, so every insert walks the whole chain and adds to its end. A search for 5 visits all five nodes: O(n), as slow as a linked list.

2. Why write node.left = insert(node.left, val) instead of just calling insert(node.left, val)?

Show answer

When node.left is null, the call creates the new node and returns it, and only the assignment links it to its parent. Elsewhere the call returns the existing child, so the assignment does no harm. Callers write root = insert(root, val) for the same reason.

3. Insert sends an equal key to the right, and search stops at the first equal node. Can a duplicate be missed?

Show answer

No. With one consistent rule, equal keys always go right, so a search finds the first copy. The bug appears when the rule isn't consistent, sometimes left and sometimes right. A search follows one direction and can walk past a copy on the other side. Ignoring duplicates, or counting them in the node, avoids the question.

Key takeaways

  • Each comparison discards a whole subtree, so search and insert walk one path: O(height).
  • Insert is a search that attaches a new node where the search falls off.
  • Height decides the cost. Sorted inserts build a chain; balanced trees stay O(log n).
  • Pick one rule for equal keys and use it everywhere.

Quick revise

The whole skill on one page, for the night before an interview.

This page puts the lesson and the deep dive together. Skim it before practice or an interview, and go back to the full lesson for anything you don't recognize.

Pick the tool

You needUse
Find or add a keyone walk: smaller goes left, larger goes right
No recursion stackiterative insert with parent
All keys known up frontsort, then build from the middle
O(log n) for any orderTreeMap / TreeSet; sortedcontainers in Python
Membership onlya hash set

Snippets worth knowing by heart

Java

TreeNode insert(TreeNode node, int val) {
    if (node == null) return new TreeNode(val);
    if (val < node.val) node.left = insert(node.left, val);
    else if (val > node.val) node.right = insert(node.right, val);
    return node;                                  // root = insert(root, val)
}

Python

def search_bst(root, val):
    cur = root
    while cur is not None and cur.val != val:
        cur = cur.left if val < cur.val else cur.right
    return cur is not None

The traps

  • Sorted input builds a chain, so every operation is O(n).
  • Mixed rules for equal keys leave copies the search never finds.
  • Not assigning the return value of the recursive insert loses the new node.
  • Quoting O(log n) for a tree that might not be balanced.

Staff-level points, one line each

  • 1,000 keys: sorted insertion gives height 999, a random order 20 (average depth 10.9), building from the sorted array 9.
  • Recursive insert of sorted keys: Python raised RecursionError on key 999; Java overflowed the stack on 100,000.
  • Red-black trees (TreeMap) guarantee h ≤ 2 log2(n + 1); 1,000,000 keys inserted in sorted order were fine.
  • Sorted collections judge equality by the comparator: TreeSet of BigDecimal 1.0 and 1.00 had size 1, HashSet size 2.
  • (a, b) -> a - b overflows: a TreeSet built with it iterated as [2000000000, -2000000000, 0].
  • Duplicates: a set, a count in the node, or always one side. Pick one.

Say it in an interview

  • "Each comparison discards a subtree, so search and insert are O(h)."
  • "h is log n only if the tree is balanced. Sorted input makes it n."
  • "If I have all the keys, I'll sort them and build from the middle."
  • "In production I'd use a red-black tree like TreeMap, not a plain BST."

Practice

This skill comes with 10 multiple-choice questions that tell you which misconception a wrong answer reveals and 2 graded problems. Your answers are graded and your mastery is tracked, so you'll know when the skill holds up. Running code and saving progress need a free account.

Practice BST Search and Insert free

Construct BST from Given Keys

MediumProCoding problemJava · Python

Given a sequence of distinct keys, build a binary search tree by inserting them one at a time, in the given order, into an initially empty tree. Return the resulting tree.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Practice BST Search and Insert free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime