Skip to content

Trees & Binary Search Trees

A hierarchy that keeps the search decision at every node: left, right, or stop

1. A hierarchy

A tree is a set of nodes connected by parent-child edges, with one root and no cycles. The root has no parent; a leaf has no children. The depth of a node is the number of edges from the root, and the height of the tree is the maximum depth. A binary tree restricts every node to at most two children.

  • Root — the entry point.
  • Subtree — a node and all of its descendants.
  • Height — the longest root-to-leaf path. This is the number that decides the cost of search.

2. The BST invariant

A binary search tree adds one rule: for every node, every key in its left subtree is smaller, and every key in its right subtree is larger. The rule is local, but it implies a global order. That is what makes search possible without scanning the whole tree.

The BST invariant

Duplicates need a policy: reject them, store a count, or consistently place them on one side. The invariant above assumes distinct keys.

4. Traversals

A traversal is an order in which to visit every node. The three depth-first orders differ only in when the node itself is visited relative to its children.

  • Inorder — left, node, right. On a BST this yields sorted order.
  • Preorder — node, left, right. Useful for copying or serializing a tree.
  • Postorder — left, right, node. Useful when children must be processed before the parent.
  • Level order — breadth-first, using a queue. Useful for printing a tree by depth.

The recursion is the traversal

Inorder is three lines: recurse left, visit, recurse right. The call stack remembers where to resume, which is why an explicit stack can replace the recursion without changing the order.

5. Balance

A BST is only as fast as its height. Insert 10, 20, 30, 40, 50 in order and every node goes to the right: the tree becomes a linked list with height n − 1, and search is O(n). A balanced tree keeps the height logarithmic by restructuring after insertions and deletions.

  • AVL tree — stores a balance factor and rotates when the heights differ by more than one.
  • Red-black tree — a color invariant that keeps the height within twice the optimal; used by many standard libraries.
  • B-tree — a multi-way balanced tree designed for disks and databases.

6. Practice

Try it

Insert 8, 3, 10, 1, 6, 14, 4, 7, 13. What is the inorder traversal?

Try it

Why is searching a degenerate BST O(n)?

Try it

Which traversal would you use to free every node in a tree?

Try it

What is the difference between a BST and a hash table for lookup?

7. Resources

Trees are the first structure in this track that keeps an order. The next lesson uses that order to sort, and the lesson after that uses a different kind of graph to search a maze.

Next: sorting →

Continue the track

Site soundtrack