Walking a tree

By levels or by branches · Part of Trees and graphs

Key idea

Practice

6 questions · about 3 min

Explained step by step

Breadth-first search (BFS)

Level-order traversal visits the tree from top to bottom, one level at a time, and left to right within each level. It's a breadth-first traversal, or BFS: it expands outward like a ripple. It's built with a queue: the root is enqueued, and each time a node is dequeued its children are enqueued. Since the queue respects arrival order, a level's nodes come out before the next level's.

Choosing between breadth and depth depends on what you're looking for. BFS finds what's closest to the root first, because it goes level by level: it's for finding the shortest path. DFS reaches the bottom of a branch first: it's for exploring every possibility along a path, as in a maze, and usually uses less memory in wide, short trees.

Depth-first search (DFS)

Depth-first traversal, or DFS, goes down one branch to the bottom before coming back and trying the other. Imagine walking around the outline of the tree, starting on the left of the root: you pass close to each node 3 times, once on its left, once below and once on its right. Depending on which of those 3 passes you write it down on, you get preorder, inorder or postorder.

To work out a traversal by hand, you apply the rule in every subtree. With root 1, left child 2 (which has 4 and 5) and right child 3: the preorder is 1, then the whole left subtree in preorder (2, 4, 5), then the right (3): 1, 2, 4, 5, 3. The inorder is 4, 2, 5, 1, 3. The postorder is 4, 5, 2, 3, 1.

Each traversal has typical uses. Preorder is for copying a tree, because it creates each parent before its children. Postorder is for deleting it or computing something bottom-up, like each folder's size. And inorder, in a search tree where smaller values go left and larger ones right, returns the values sorted from smallest to largest.

Every traversal visits each node once, so they cost O(n) in time. In memory they can also reach O(n). Breadth-first, a perfect tree's queue holds about n/2 nodes just before the last level. Depth-first, if the tree is lopsided like a list, the recursion reaches depth n and the call stack holds n frames.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

By levels or by branches