Data Structures · Visualization

BST: Search

Binary Search Tree

Searching a BST uses its ordering rule to eliminate half the remaining tree at each step, similar to binary search on a sorted array. 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: Search

Binary Search Tree

Searching a BST uses its ordering rule to eliminate half the remaining tree at each step, similar to binary search on a sorted array. Starting at the root, you compare the target with the current node and move left or right accordingly, discarding the other side entirely, until you find the value or hit an empty spot.

How Search Works

  1. Start at the root.
  2. If the current node is null, the value is not in the tree.
  3. If the current node's value matches the target, return it (found).
  4. If the target is smaller, move to the left child; if larger, move to the right child.
  5. Repeat until found or you reach null.

Search Worked Example

Input: Search for 6 in root(8) -> left(3) -> right(6)

  1. Compare 6 with root(8): 6 < 8, go left
  2. Compare 6 with node(3): 6 > 3, go right
  3. Compare 6 with node(6): match found!

Output: Found

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 search(root, val):
    cur = root
    while cur and cur.val != val:
        if val < cur.val:
            cur = cur.left      # go left
        else:
            cur = cur.right     # go right
    return cur                  # None if missing

# Halves the tree each step: O(log n)
# example: search 6
Input: Search for 6 in root(8) -> left(3) -> right(6)

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.

Search Time & Space Complexity

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

When to Use Search

  • Fast membership checks in a sorted, dynamic dataset
  • Auto-complete or dictionary-style lookups
  • Range and nearest-neighbor queries on ordered data

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.