Data Structures19 sections · 729 units
Open in Course

BST Search

Binary search in tree form

Search follows the BST property directly:

def search(root, target):
    if root == null:
        return null
    if target == root.val:
        return root
    if target < root.val:
        return search(root.left, target)
    else:
        return search(root.right, target)

Iterative version:

def search(root, target):
 while root and root.val != target:
 if target < root.val:
 root = root.left
 else:
 root = root.right
 return root

Time: O(h)O(h) where hh is tree height.

Space: O(1)O(1) for iterative, O(h)O(h) for recursive.

In a balanced tree, h=O(logn)h = O(\log n). In the worst case (skewed), h=O(n)h = O(n).