Find a course

Module 4: Trees and HeapsLesson 10 of 1314 min

Trees and Binary Search Trees

Learn tree vocabulary, search and insert in a binary search tree, see why balance decides its speed, and traverse trees in order, preorder and postorder.

Step 1 of 11Learn

Data with a hierarchy

Many kinds of data are naturally hierarchical: folders inside folders on your computer, elements inside elements in a web page, managers and reports in an organization, categories and subcategories in a store. The data structure for hierarchy is the tree.

A tree is made of nodes connected by edges, with these properties and terms:

  • One node at the top is the root.
  • Every other node has exactly one parent; nodes below a node are its children.
  • A node with no children is a leaf.
  • Any node together with everything below it forms a subtree.
  • The depth of a node is the number of edges from the root to it. The height of a tree is the greatest depth of any node, the length of the longest root-to-leaf path. (Some texts count nodes instead of edges, so always check which convention is in use.)
  • Trees have no cycles: there's exactly one path between the root and any node.

In a binary tree, each node has at most two children, called left and right. Binary trees are the basis for binary search trees, heaps and many other structures.

Trees are recursive by nature: a binary tree is either empty, or a root node with a left binary tree and a right binary tree. That's why recursive functions fit trees so well. To count nodes, add one for the root to the counts of the left and right subtrees; the base case is an empty tree with zero nodes.

Tree vocabulary: root at the top, parents and children, leaves at the bottomroot (depth 0)child (depth 1)leaf (depth 2)leafchildleafHeight = 2: edges on the longest root-to-leaf path

Step 2 of 11Practice · Match the pairs

Match each tree term to its definition.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Root
  2. Leaf
  3. Depth of a node
  4. Height of a tree
  5. Subtree

Step 3 of 11Learn

Binary search trees

A binary search tree (BST) is a binary tree with an ordering rule: for every node, all keys in its left subtree are smaller than its key, and all keys in its right subtree are larger.

That rule makes searching like binary search. To find a key, start at the root. If the key equals the node's key, you're done. If it's smaller, go left; if larger, go right. Repeat until you find it or reach an empty spot, meaning the key isn't there. Insertion follows the same path and attaches the new node where the search ended.

Each step moves one level down, so search and insert take O(h) time, where h is the tree's height. Everything depends on h:

  • In a balanced tree, each level roughly doubles the number of nodes, so h is about log₂ n. A balanced BST with a million keys has a height of about 20: O(log n) operations.
  • In a degenerate tree, every node has only one child, and the tree is really a linked list with h = n − 1: O(n) operations. This happens if you insert keys in sorted order, such as 1, 2, 3, 4, 5: each new key goes to the right of the last.

Self-balancing BSTs, such as AVL trees and red-black trees, fix this by rotating nodes after insertions and deletions to keep the height O(log n) guaranteed. Many standard libraries use red-black trees for their sorted maps and sets, such as Java's TreeMap and C++'s std::map.

A binary search tree: smaller keys to the left, larger to the right; searching for 6 follows 8, 3, 6831647101413Inorder traversal gives 1, 3, 4, 6, 7, 8, 10, 13, 14 (sorted)

Step 4 of 11Practice · Work it out

Insert the keys 10, 5, 15, 3, 7, 20 in that order into an empty binary search tree. What is the height of the resulting tree, counting edges on the longest root-to-leaf path?

Step 5 of 11Learn

Tree traversals

To visit every node in a tree, there are several standard orders. For binary trees, three are depth-first and defined recursively by when you visit the node relative to its subtrees:

  • Preorder: node, then left subtree, then right subtree. Useful for copying a tree or printing a folder structure top-down.
  • Inorder: left subtree, then node, then right subtree. On a BST, inorder visits keys in sorted order, which gives you a sorted list in O(n).
  • Postorder: left subtree, then right subtree, then node. Useful when children must be processed before parents, such as computing folder sizes or freeing memory.

There's also level-order traversal, which visits nodes level by level from the root, left to right. It's breadth-first search on a tree and uses a queue.

Take a BST with root 8; 8's left child is 3 and right child is 10; 3 has children 1 and 6; 10 has a right child 14.

  • Preorder: 8, 3, 1, 6, 10, 14
  • Inorder: 1, 3, 6, 8, 10, 14
  • Postorder: 1, 6, 3, 14, 10, 8
  • Level-order: 8, 3, 10, 1, 6, 14

Each traversal visits every node once: O(n) time. The recursive versions use stack space proportional to the height.

Step 6 of 11Practice · Diagram

Traversals on a small BST

Preorder: 40, 20, 10, 30, 60, 50, 70. Inorder: 10, 20, 30, 40, 50, 60, 70. Postorder: 10, 30, 20, 50, 70, 60, 40.

Tap the key that an inorder traversal of this tree visits first.

Tap the shape that answers the question, then press Check.

Traversals on a small BSTHierarchy diagram: 40, 20, 60, 10, 30, 50, 70.40206010305070
40

The root: preorder visits it first, postorder last.

20
60
10

The leftmost node holds the smallest key.

30
50
70

The rightmost node holds the largest key.

Step 7 of 11Practice · Put in order

A BST has root 50; its left child is 30 and right child is 70; 30 has children 20 and 40; 70 has a right child 80. Put the keys in the order a preorder traversal visits them.

Drag the items, or use the arrow buttons, to put them in order.

  1. 30
  2. 40
  3. 50
  4. 70
  5. 80
  6. 20

Step 8 of 11Practice · Code challenge

Nodes look like { val, left, right }, with null for a missing child. Write a recursive treeHeight(node) that returns the number of nodes on the longest root-to-leaf path. An empty tree (null) has height 0 and a single node has height 1.

Runs in a sandbox in your browser.
  • treeHeight(null)
  • treeHeight({ val: 5, left: null, right: null })
  • treeHeight({ val: 8, left: { val: 3, left: { val: 1, left: null, right: null }, right: null }, right: { val: 10, left: null, right: null } })
  • treeHeight({ val: 1, left: null, right: { val: 2, left: null, right: { val: 3, left: null, right: { val: 4, left: null, right: null } } } })

Step 9 of 11Learn

BST, hash table or sorted array?

If hash tables give O(1) average lookups, why use a BST with O(log n)? Because a BST keeps keys in order, and many operations need that order:

  • Minimum and maximum: follow left or right pointers to the end, O(h).
  • Successor and predecessor: the next larger or smaller key.
  • Range queries: all keys between 100 and 200, in O(h + k) for k results.
  • Sorted iteration: an inorder traversal lists all keys in order in O(n).

A hash table can't do any of these efficiently; it would have to examine every key. A sorted array supports them with binary search, but inserting or deleting costs O(n) because of shifting. A balanced BST offers O(log n) for search, insert, delete and ordered operations, a good all-round compromise.

Deleting from a BST has three cases. A leaf is simply removed. A node with one child is replaced by that child. A node with two children is replaced by its inorder successor, the smallest key in its right subtree, which is then removed from its old position.

In practice, use your language's library: hash maps when you only need lookups by key, and tree-based sorted maps when you need order. Databases use a close relative, the B-tree, which has many keys per node so that each node fits a disk page and the tree stays very shallow.

Step 10 of 11Practice · True or false

Searching any binary search tree is guaranteed to take O(log n) time.

Step 11 of 11Practice · Choose one

Which task does a balanced binary search tree handle much better than a hash table?