Data Structures · Visualization

BST: Insert

Binary Search Tree

Inserting into a BST means finding the correct empty spot according to the ordering rule (smaller goes left, larger goes right) and placing the new node there. Time: O(h), O(log n) average, O(n) worst case. Space: O(h) recursive, O(1) iterative.

Big-O: Search/insert/delete O(log n) on a balanced tree, O(n) worst case.

BST: Insert

Binary Search Tree

Inserting into a BST means finding the correct empty spot according to the ordering rule (smaller goes left, larger goes right) and placing the new node there. You compare the new value against each node starting from the root, moving left or right, until you find an empty spot to attach it.

How Insert Works

  1. Start at the root.
  2. If the tree is empty, the new value becomes the root and you're done.
  3. Compare the new value with the current node: if smaller, move left; if larger, move right.
  4. Repeat until you reach an empty (null) spot.
  5. Attach the new node there.

Insert Worked Example

Input: Insert 5 into a BST with root 8, left child 3

  1. Compare 5 with root(8): 5 < 8, go left
  2. Compare 5 with node(3): 5 > 3, go right
  3. Node(3)'s right child is empty — attach 5 there

Output: 8 / 3 \ 5

Try your own input
BST: Introduction
A binary tree with a rule: every left descendant is smaller than its parent, and every right descendant is bigger — which makes searching fast.
45
20
10
30
40
65
50
60
70
80
Active Result
BST: Introduction
Press ▶ Run to watch it step by step.
Python · Binary Search Trees in Code
def insert(root, val):
    if not root:
        return Node(val)
    if val < root.val:
        root.left = insert(root.left, val)
    else:
        root.right = insert(root.right, val)
    return root

# O(log n) on a balanced tree
# example: insert 5
Input: Insert 5 into a BST with root 8, left child 3

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Insert Time & Space Complexity

TimeO(h), O(log n) average, O(n) worst case
SpaceO(h) recursive, O(1) iterative

When to Use Insert

  • Building a searchable, sorted structure from a stream of incoming values
  • Maintaining leaderboard or ranking data with fast updates
  • Any application needing sorted-order insertion without full re-sorting

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.