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 TreeIn 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
- Start at the root.
- If the current node is null, the value is not found on this path.
- If the current node's value matches the target, return it (found).
- Otherwise, recursively search the left subtree and the right subtree.
Search Worked Example
Input: Search for 7 in root(10) -> left(5), right(7)
- Check root(10): no match
- Search left subtree: check 5, no match, no children
- Search right subtree: check 7, match found!
Output: Found (root's right child)
Press ▶ Run to watch it step by step.
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 7Behind 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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.