Algorithms Playbook
Data structureTime O(h) · Space O(1)7 min read

Binary search trees: search, insert and validate

The ordering rule of a BST, why search takes O(h), and the classic validation trap that trips up most candidates.

In short

In a binary search tree every node is bigger than everything in its left subtree and smaller than everything in its right. Search, insert and delete follow one path: O(h), which is O(log n) if balanced and O(n) if it degenerates into a chain.

Operations and shapes

OperationBalancedDegenerate chain
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
Sorted orderInorder, O(n)Inorder, O(n)

Inserting already-sorted values builds a chain. Self-balancing trees (AVL, red-black) keep the height at log n; in practice they power TreeMap in Java and ordered sets elsewhere.

The classic trap: validating a BST

Checking only left < node < right for each node is wrong: a node deep in the left subtree can still be bigger than the root. Each node must fit inside a range inherited from all its ancestors.

def is_valid(node, lo=float('-inf'), hi=float('inf')):
    if not node: return True
    if not (lo < node.val < hi): return False
    return (is_valid(node.left, lo, node.val) and
            is_valid(node.right, node.val, hi))

Key takeaways

  • 01BST rule: left subtree < node < right subtree, at every node.
  • 02Search, insert, delete cost O(h): log n if balanced, n if a chain.
  • 03Validate with a (lo, hi) range, not just the two children.
  • 04Inorder traversal of a BST is sorted.

Check your understanding

1 of 3

Search in a balanced BST costs…

Related topics