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 TreeSearching 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
- Start at the root.
- If the current node is null, the value is not in the tree.
- If the current node's value matches the target, return it (found).
- If the target is smaller, move to the left child; if larger, move to the right child.
- Repeat until found or you reach null.
Search Worked Example
Input: Search for 6 in root(8) -> left(3) -> right(6)
- Compare 6 with root(8): 6 < 8, go left
- Compare 6 with node(3): 6 > 3, go right
- Compare 6 with node(6): match found!
Output: Found
Press ▶ Run to watch it step by step.
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 6Behind 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
- 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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.