Lesson contents

Trees and traversals

A tree links a parent to its children. A rooted tree has one path from the root to each node. Traversal is the order in which you visit them.

Simple example

Node 2 has left child 1 and right child 3. For an inorder walk, visit the left child, then its parent, then the right child.

Start2→1,3
Result1 2 3
lesson.c
#include <stdbool.h>
#include <stdio.h>

int main(void) {
    int keys[] = {2, 1, 3};
    int left[] = {1, -1, -1};
    int right[] = {2, -1, -1};
    int stack[] = {0, 0, 0};
    int size = 0;
    int node = 0;
    while ((node != -1) || (size > 0)) {
        while (node != -1) {
            stack[size] = node;
            size += 1;
            node = left[node];
        }
        size -= 1;
        node = stack[size];
        printf("%d\n", keys[node]);
        node = right[node];
    }
}
Output
1
2
3
Advertisements

Everyday examples

List folders before their contents

Folder A holds folders B and C. List each folder before visiting its children, left to right. What order appears?

StartA→B,C
ResultA B C

A preorder walk lists A first, then the contents of B, then the contents of C.

Pack smaller boxes first

Box A contains boxes B and C. Each inner box must be sealed before its outer box. When can A be sealed?

StartA→B,C
ResultB C A

A postorder walk finishes both children before the parent. A is sealed last.

Announce a club by level

Chair A leads captains B and C. B leads D. Which announcement order reaches the captains before the member?

StartA→B,C B→D
ResultA B C D

Visit one level at a time. A queue keeps D waiting until both captains have been announced.

Cost and limits

Visiting every node takes linear time. An inorder walk sorts values only when the tree also follows the binary search tree ordering rule.