Data Structures · Visualization

Binary Tree: Search

Binary Tree

In a general binary tree (with no ordering guarantee), finding a value requires checking every node, because there is no rule telling you whether to go left or right. Time: O(n) — every node may need to be checked. Space: O(h) for recursion, where h is the tree height.

Big-O: Traversals visit every node exactly once: O(n).

Binary Tree: Search

Binary Tree

In a general binary tree (with no ordering guarantee), finding a value requires checking every node, because there is no rule telling you whether to go left or right. This is done with a traversal — often depth-first — that visits nodes until a match is found.

How Search Works

  1. Start at the root.
  2. If the current node is null, the value is not found on this path.
  3. If the current node's value matches the target, return it (found).
  4. Otherwise, recursively search the left subtree and the right subtree.

Search Worked Example

Input: Search for 7 in root(10) -> left(5), right(7)

  1. Check root(10): no match
  2. Search left subtree: check 5, no match, no children
  3. Search right subtree: check 7, match found!

Output: Found (root's right child)

Try your own input
Binary Tree: Introduction
A hierarchy of nodes where each node has at most two children — usually called "left" and "right".
45
20
10
30
40
65
50
60
70
80
Active Result
Binary Tree: Introduction
Press ▶ Run to watch it step by step.
Python · Binary Trees in Code
def search(root, val):
    while root and root.val != val:
        if val < root.val:
            root = root.left   # go left
        else:
            root = root.right  # go right
    return root  # None if absent
# example: search 7
Input: Search for 7 in root(10) -> left(5), right(7)

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(n) — every node may need to be checked
SpaceO(h) for recursion, where h is the tree height

When to Use Search

  • Checking whether a value exists anywhere in a general hierarchical structure
  • Searching an unordered decision tree or category tree
  • A baseline compared against faster BST search

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.