Chapter 10: Trees
Introduction
Learning Outcomes
Point out root, parent, child, sibling, ancestor, descendant, degree, level, depth, and leaf on a tree.
Prove the lemma (2i−1, 2k−1); tell perfect, complete, and incomplete trees apart.
Represent trees with an array (parent = ⌊i/2⌋) and with links (tree_pointer); compare their memory cost.
Write preorder, inorder, and postorder recursively and iteratively with a stack; traverse level by level.
Build recursive routines for printing leaves, copying, equivalence, and swapping left and right.
Justify the O(n) time and O(h) memory of each routine.
Terminology
Trees: a hierarchy where each node has one parent
- Searching, sorting, data compression, syntax analysis, code optimization, compiler internals…
- In everyday life: family trees, an organization chart, a file system.
- A tree is a special kind of graph: in a tree every node has exactly one parent; in a graph a node can have several.
- Every subtree is itself a tree → tree routines are naturally recursive.
Terminology
Terminology on an example tree
B is the parent of E and F; E and F are B's children. Children of the same parent are siblings.
The number of subtrees of a node: A has degree 3, F degree 0 (the small numbers at the upper right).
A node of degree 0: K, L, F, G, M, I, J.
Terminology
Terminology step by step
The root is A. Levels are numbered from the root: in this course the root is at level 1.
A node with subtrees is the parent of their roots, and they are its children.
Children of the same parent are siblings. The family terms extend to other generations: grandparent, grandchild.
The ancestors of a node are all the nodes on the path from the root to it. D is M's grandparent.
All the nodes in a node's subtree are its descendants. Children's children are grandchildren: E, F, G, H, I, J are A's grandchildren.
Nodes of degree 0 are called leaves or terminal nodes.
The degree of a tree is the largest node degree (3); its depth is the largest level number (4).
Degree and depth are different concepts; defining both as “the maximum of the degrees” is a common mistake.
Terminology
Depth and height: books count differently
- This course (Horowitz–Sahni): the root is at level 1; the tree's depth = the largest level = the longest path counted in nodes. 4 in the example tree.
- CLRS / Sedgewick: the root has depth 0; height = the number of edges from the root to the farthest leaf. 3 for the same tree.
- State which definition you are using on an exam; the formulas shift by 1 accordingly.
- In this chapter
depth(NULL) = 0, and a one-node tree has depth 1.
| concept | this course | CLRS |
|---|---|---|
| level of the root | 1 | 0 |
| level of M | 4 | 3 |
| depth of the tree | 4 | height 3 |
| empty tree | 0 | −1 |
Binary Trees
Binary trees
- Each node has a left subtree, a right subtree, both, or neither.
- Node degrees can be 0, 1, or 2.
- Left and right are distinct: for a node with one child, it matters whether the child is on the left or the right.
- As sets: binary trees ⊂ trees ⊂ graphs.
Binary Trees
Lemma: the maximum number of nodes on a level and in a tree
i) The maximum number of nodes on level i is 2i−1 (i ≥ 1). Base: for i = 1, 20 = 1 (the root alone).
Induction: if level n−1 has 2n−2 nodes, each with at most 2 children, then level n has 2·2n−2 = 2n−1 nodes.
ii) A binary tree of depth k has at most 2k − 1 nodes: Σi=1..k 2i−1 = 20 + 21 + … + 2k−1.
The geometric sum gives 2k − 1. k = 4 → at most 15 nodes. A lemma: “a milder form of a theorem whose truth is easy to see.”
Binary Trees
Perfect and complete binary trees
A binary tree of depth k with 2k − 1 nodes: every level is full.
A tree with n nodes that can be numbered 1 to n without gaps when a parent gets i, its left child 2i, and its right child 2i+1.
A complete tree fits in an array with no gaps, and its depth ⌈lg(n+1)⌉ is the smallest possible.
Binary Trees
Relations between depth and node count
- For a binary tree of depth k: k ≤ n ≤ 2k − 1; hence ⌈lg(n+1)⌉ ≤ k ≤ n.
- A complete tree has the smallest depth: k = ⌈lg(n+1)⌉ = ⌊lg n⌋ + 1.
- n0 = n2 + 1: there is one more leaf than there are nodes with two children. Proof: n = n0+n1+n2 and the number of edges is n−1 = n1+2n2.
- Of the 2n pointer fields, n−1 are in use → n+1 NULL pointers (the starting point for threaded binary trees).
Source: Horowitz–Sahni–Anderson-Freed, Lemma 5.2–5.3; CLRS B.5.
Representation
Representing a binary tree in an array
- A complete binary tree with n nodes can be laid out in an array.
- Because of the formulas, indexing starts at 1, not 0!
parent(i) = ⌊i/2⌋(if i = 1, it is the root)left_child(i) = 2i(no left child if 2i > n)right_child(i) = 2i+1(no right child if 2i+1 > n)- For depth k, allocate an array of 2k − 1 cells.
#define MAX_NODES 63 /* 2^k - 1 */ char tree[MAX_NODES + 1]; /* [0] unused */ int n; /* node count */ int parent(int i) { return i / 2; } int left_child(int i) { return 2 * i; } int right_child(int i) { return 2 * i + 1; } /* has a child? left_child(i) <= n */
Representation
Memory in the array representation: complete vs. skewed trees
Complete tree: almost every cell of the array is filled; little or no memory is wasted.
The further a tree is from complete, the more memory sits idle. A left-skewed tree of depth 5 needs 31 cells and uses 5.
Representation
Linked (pointer) representation of a binary tree
typedef struct node *tree_pointer; struct node { tree_pointer left_child; /* left subtree */ char data; tree_pointer right_child; /* right subtree */ };
- Each node: a left pointer, the data, a right pointer.
- Insertion and deletion are just pointer assignments.
- An empty subtree is NULL (dark box).
Representation
A new node: get_node()
tree_pointer get_node(void) { /* new node */ tree_pointer p = malloc(sizeof *p); if (p == NULL) { fprintf(stderr, "Out of memory!\n"); exit(EXIT_FAILURE); } p->left_child = p->right_child = NULL; return p; } void tree_free(tree_pointer L) { /* postorder */ if (!L) return; tree_free(L->left_child); tree_free(L->right_child); free(L); }
get_node() checks the result of malloc and sets the children to NULL; every example uses it.- Freeing a tree must go in postorder: if the root is freed first, the pointers to its children are lost.
Representation
Array or linked representation?
Array
- No pointer fields; O(1) index arithmetic to reach a parent or child.
- No wasted memory for a complete tree.
- A good fit when, say, the computers on a network are fixed and won't be added or removed later.
Linked representation
- 2 pointers per node; even a skewed tree needs only n nodes.
- Insertion and deletion are pointer assignments.
- No direct access to the parent (add a
parentfield if needed).
Representation
Turning a general tree into a binary tree: left child, right sibling
In a general tree the number of children varies from node to node; it is hard to hold with a fixed-field struct.
Each node keeps a link only to its first child; siblings are chained together through a right sibling link.
First child = left pointer, right sibling = right pointer: the result is a binary tree. The root's right link is always NULL.
struct gnode { char data; struct gnode *child; /* = left */ struct gnode *sibling; /* = right */ };
- The binary tree's preorder = the general tree's preorder.
- The binary tree's inorder = the general tree's postorder. (Horowitz 5.1.2; Knuth 2.3.2)
Traversals
Binary tree traversals
- Goal: visit every node of the tree exactly once.
- At a node there are three things: the data (V), the left subtree (L), and the right subtree (R) → 3! = 6 traversal orders.
- The three that visit left before right are standard: inorder, preorder, postorder.
- The other three (right to left) can be used if needed.
| order | name | |
|---|---|---|
| 1 | Left – Data – Right | inorder |
| 2 | Left – Right – Data | postorder |
| 3 | Data – Left – Right | preorder |
| 4 | Right – Data – Left | reverse inorder |
| 5 | Right – Left – Data | reverse postorder |
| 6 | Data – Right – Left | reverse preorder |
Traversals
An arithmetic expression tree and three notations
- Inorder → infix:
((((A/B)*C)*D)+E) - Preorder → prefix:
+**/ABCDE - Postorder → postfix:
AB/C*D*E+ - Interior nodes are operators (orange), leaves are operands. The parentheses are stored in the tree's shape and are added back when writing infix.
- Compilers turn expressions into trees like this; the postfix form is evaluated with a stack.
Traversals
Same tree, three traversals
Preorder (V-L-R): the root first, then the whole left subtree, then the right subtree → ABCDGHEIJKFL
Inorder (L-V-R): B's left is empty, so B is printed first → BGDHCEJIKALF
Postorder (L-R-V): the root always comes last; A is the last letter → GHDJKIECBLFA
Traversals
Traversal routines, recursively
void preorder(tree_pointer L) { if (L) { printf("%c", L->data); preorder(L->left_child); preorder(L->right_child); } }
void inorder(tree_pointer L) { if (L) { inorder(L->left_child); printf("%c", L->data); inorder(L->right_child); } }
void postorder(tree_pointer L) { if (L) { postorder(L->left_child); postorder(L->right_child); printf("%c", L->data); } }
The three routines share one skeleton; only the position of the printf line changes. if (L) handles both the empty tree and the recursion's stopping condition.
Traversals · Run the code step by step
Inorder traversal step by step (with the call stack)
L = A: call inorder(B) for the left subtree; this frame waits.
L = B: call inorder(D) for the left subtree; this frame waits.
L = D: call inorder(NULL) for the left subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (D has no left child).
L = D: the left subtree is done; now print the root → D is added to the output.
L = D: call inorder(NULL) for the right subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (D has no right child).
L = B: the left subtree is done; now print the root → B is added to the output.
L = B: call inorder(NULL) for the right subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (B has no right child).
L = A: the left subtree is done; now print the root → A is added to the output.
L = A: call inorder(C) for the right subtree; this frame waits.
L = C: call inorder(NULL) for the left subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (C has no left child).
L = C: the left subtree is done; now print the root → C is added to the output.
L = C: call inorder(NULL) for the right subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (C has no right child).
All calls have returned. Output: DBAC. Each node was entered once and left once: 2n steps.
void inorder(tree_pointer L) { if (L) { inorder(L->left_child); printf("%c", L->data); inorder(L->right_child); } }
Traversals · Run the code step by step
Preorder traversal step by step
L = A: preorder prints itself first → A is added to the output.
L = A: call preorder(B) for the left subtree; this frame waits.
L = B: preorder prints itself first → B is added to the output.
L = B: call preorder(D) for the left subtree; this frame waits.
L = D: preorder prints itself first → D is added to the output.
L = D: call preorder(NULL) for the left subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (D has no left child).
L = D: call preorder(NULL) for the right subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (D has no right child).
L = B: call preorder(NULL) for the right subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (B has no right child).
L = A: call preorder(C) for the right subtree; this frame waits.
L = C: preorder prints itself first → C is added to the output.
L = C: call preorder(NULL) for the left subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (C has no left child).
L = C: call preorder(NULL) for the right subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (C has no right child).
All calls have returned. Output: ABDC. Each node was entered once and left once: 2n steps.
void preorder(tree_pointer L) { if (L) { printf("%c", L->data); preorder(L->left_child); preorder(L->right_child); } }
Traversals · Run the code step by step
Postorder traversal step by step
L = A: call postorder(B) for the left subtree; this frame waits.
L = B: call postorder(D) for the left subtree; this frame waits.
L = D: call postorder(NULL) for the left subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (D has no left child).
L = D: call postorder(NULL) for the right subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (D has no right child).
L = D: both subtrees are done; the root is printed last → D is added to the output.
L = B: call postorder(NULL) for the right subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (B has no right child).
L = B: both subtrees are done; the root is printed last → B is added to the output.
L = A: call postorder(C) for the right subtree; this frame waits.
L = C: call postorder(NULL) for the left subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (C has no left child).
L = C: call postorder(NULL) for the right subtree; this frame waits.
L == NULL → if (L) is false; the call returns without doing anything (C has no right child).
L = C: both subtrees are done; the root is printed last → C is added to the output.
L = A: both subtrees are done; the root is printed last → A is added to the output.
All calls have returned. Output: DBCA. Each node was entered once and left once: 2n steps.
void postorder(tree_pointer L) { if (L) { postorder(L->left_child); postorder(L->right_child); printf("%c", L->data); } }
Traversals
The cost of traversal, and NULL calls
- Time: each node is entered once and left once → 2n = O(n), always.
- Memory: the call stack holds at most as many frames as the depth (h) → O(h). O(lg n) for a balanced tree; O(n) for a skewed one.
- A tree with n nodes makes n+1 calls on NULL. Checking before the call removes them:
/* before: n+1 calls on NULL */ preorder(L->left_child); preorder(L->right_child); /* after: check before calling */ if (L->left_child) preorder(L->left_child); if (L->right_child) preorder(L->right_child);
The if (L) in the first call must stay: the tree may be empty. The O(lg n) memory bound holds only for balanced trees; the general bound is O(h).
Traversals
You learn recursive code by writing it yourself
— Chinese proverb
Each call is a node and each subcall a child: the call tree of a traversal is the tree itself, with the NULL calls as leaves (n internal + n+1 leaves).
Traversals
Evaluating an expression tree: postorder traversal
typedef struct expr *expr_pointer; struct expr { char op; /* '+', '-', '*', '/' */ int value; /* leaves only */ expr_pointer left, right; };
- An operator's value can't be computed until the values of both subexpressions are known → left first, then right, the root last: postorder.
- Every interior node has exactly two children (binary operators); a leaf holds a number, not an operator.
- Cost: O(n) time, O(h) stack. Unary minus (−x) would need a node with one child.
Traversals · Run the code step by step
eval(): (8 / 4) * 3 + 5 = 11
+ is an operator: evaluate the left subexpression first.
* is an operator: evaluate the left subexpression first.
/ is an operator: evaluate the left subexpression first.
8 is a leaf: it returns its number → 8.
Left value a = 8. Now evaluate the right subexpression.
4 is a leaf: it returns its number → 4.
b = 4; 8 / 4 = 2 is returned (postorder: left, right, root).
Left value a = 2. Now evaluate the right subexpression.
3 is a leaf: it returns its number → 3.
b = 3; 2 * 3 = 6 is returned (postorder: left, right, root).
Left value a = 6. Now evaluate the right subexpression.
5 is a leaf: it returns its number → 5.
b = 5; 6 + 5 = 11 is returned (postorder: left, right, root).
int eval(expr_pointer t) { if (!t->left && !t->right) /* leaf: a number */ return t->value; int a = eval(t->left); int b = eval(t->right); switch (t->op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; default: return a / b; } }
Iterative Traversal
Iterative traversal: where does the stack come from?
- Every recursive algorithm can be made iterative. Two ways: (1) express the behavior with a loop, or (2) push return addresses onto a stack, as the operating system does.
- Inorder: the left subtree must be printed before the root → we want the most recently added node first: LIFO.
- To keep the space cost down, the stack holds the nodes' addresses, not copies of them.
- The stack never holds more than the left depth of the tree at once.
Iterative Traversal
Non-recursive inorder traversal
void iter_inorder(tree_pointer L) { tree_pointer stack[MAX_SIZE]; int top = -1; for (;;) { for (; L; L = L->left_child) // go left push(&top, L, stack); L = pop(&top, stack); // or NULL if (!L) break; printf("%c", L->data); L = L->right_child; } }
void push(int *top, tree_pointer p, tree_pointer s[]) { if (*top == MAX_SIZE - 1) { fprintf(stderr, "Stack is full\n"); exit(EXIT_FAILURE); } s[++*top] = p; } tree_pointer pop(int *top, tree_pointer s[]) { return (*top == -1) ? NULL : s[(*top)--]; }
On an empty stack pop returns NULL: the loop's only exit.
Iterative Traversal · Run the code step by step
Inorder with a stack: A(B(D,E),C)
Push A (its address!), then go left: L = A->left_child = B.
Push B (its address!), then go left: L = B->left_child = D.
Push D (its address!), then go left: L = D->left_child = NULL. L is NULL → the inner loop ends.
Pop D; its left side is done → print D.
L = D->right_child = NULL: no right subtree, continue from the stack.
Pop B; its left side is done → print B.
L = B->right_child = E: the right subtree is traversed the same way.
Push E (its address!), then go left: L = E->left_child = NULL. L is NULL → the inner loop ends.
Pop E; its left side is done → print E.
L = E->right_child = NULL: no right subtree, continue from the stack.
Pop A; its left side is done → print A.
L = A->right_child = C: the right subtree is traversed the same way.
Push C (its address!), then go left: L = C->left_child = NULL. L is NULL → the inner loop ends.
Pop C; its left side is done → print C.
L = C->right_child = NULL: no right subtree, continue from the stack.
The stack is empty: pop returns NULL → break. The traversal is done.
void iter_inorder(tree_pointer L) { tree_pointer stack[MAX_SIZE]; int top = -1; for (;;) { for (; L; L = L->left_child) // push lefts push(&top, L, stack); L = pop(&top, stack); // NULL if empty if (!L) break; printf("%c", L->data); L = L->right_child; } }
Iterative Traversal
Cost, and printing selectively
- Each node is pushed once and popped once: 2n steps → O(n) time.
- Memory: the stack is O(h) in the worst (skewed) case; for a right-skewed tree it never holds more than 1 item → O(1).
- Put a condition on line 9 (the printf) and you get a routine that prints only selected nodes: leaves, nodes with one child, nodes with a left child…
- The condition
if(!(L->right_child)||!(L->left_child))prints nodes with at most one child; for leaves only you need&&.
— Alan J. Perlis
Iterative Traversal
Questions: write it by changing the traversal pattern
- Write the preorder traversal iteratively.
- Write the postorder traversal iteratively. (This one is harder.)
- A recursive routine that prints the leaves left to right.
- A recursive routine that prints the leaves right to left.
- An iterative routine that prints the leaves left to right.
- An iterative routine that prints the leaves right to left.
- A recursive routine that prints the nodes with only a left child.
- A recursive routine that prints the nodes with only a right child.
- A recursive routine that prints the nodes with both children.
left_child and right_child.Iterative Traversal
Q1: iterative preorder
void iter_preorder(tree_pointer L) { tree_pointer stack[MAX_SIZE]; int top = -1; for (;;) { for (; L; L = L->left_child) { printf("%c", L->data); // print on entry push(&top, L, stack); } L = pop(&top, stack); if (!L) break; L = L->right_child; } }
- The same as the iterative inorder code; only the
printfhappens as the node is pushed. - So the root is printed before its left subtree: V-L-R.
- Alternative: push the root; at each step pop a node, print it, and push its right child and then its left.
Show the second solution
if (L) push(&top, L, stack); while ((L = pop(&top, stack))) { printf("%c", L->data); if (L->right_child) push(&top, L->right_child, stack); if (L->left_child) push(&top, L->left_child, stack); }
Iterative Traversal
Q2: iterative postorder — why is it harder?
- A node reaches the top of the stack twice before it is popped: once back from its left subtree and once back from its right subtree.
- To know which one we're returning from, we keep the last node printed (
last). - If the top node t has a right child that wasn't the last one printed → go right first; otherwise print t and pop it.
- Alternative: two stacks (reverse the V-R-L order in the second stack).
Iterative Traversal · Run the code step by step
Q2 step by step: A(B(D),C)
Push L = A and go left: L = B.
Push L = B and go left: L = D.
Push L = D and go left: L = NULL.
Top is D: no right child → print D and pop it; last = D.
Top is B: no right child → print B and pop it; last = B.
Top is A: its right child C exists and hasn't been printed → right subtree first (L = C).
Push L = C and go left: L = NULL.
Top is C: no right child → print C and pop it; last = C.
Top is A: its right child C was just printed (last) → print A and pop it; last = A.
L is NULL and the stack is empty: the loop ends. The root came last: postorder.
void iter_postorder(tree_pointer L) { tree_pointer stack[MAX_SIZE], last = NULL, t; int top = -1; while (L || top != -1) { if (L) { // go left push(&top, L, stack); L = L->left_child; } else { t = stack[top]; // peek at the top if (t->right_child && t->right_child != last) L = t->right_child; // right first else { printf("%c", t->data); last = pop(&top, stack); } } } }
Iterative Traversal
Q3–6: printing the leaves
void print_leaves(tree_pointer L) { if (L) { print_leaves(L->left_child); if (!L->left_child && !L->right_child) printf("%c", L->data); print_leaves(L->right_child); } }
The solution to Q3. On the example tree (A…L) the output is GHJKL.
Q4: right to left (recursive)
Swap the order of the calls: L->right_child first, then L->left_child. Output: LKJHG.
Q5: left to right (iterative)
In the iterative inorder code, make the printf line conditional:
if (!L->left_child && !L->right_child) printf("%c", L->data);
Q6: right to left (iterative)
Swap left_child ↔ right_child throughout the iterative code: push the rights, and after a pop go left. The leaves come out in reverse order.
Iterative Traversal
Q7–9: selecting nodes by number of children
void print_left_only(tree_pointer L) { /* Q7 */ if (!L) return; if (L->left_child && !L->right_child) printf("%c", L->data); print_left_only(L->left_child); print_left_only(L->right_child); }
Q8: only a right child
Condition: !L->left_child && L->right_child.
Q9: two children
Condition: L->left_child && L->right_child. On the example tree: ACDI (in preorder).
!L->left_child = “has no left child.”On the example tree, only a left child: F; only a right child: BE.
Other Routines
QUESTION: print the nodes level by level — method I
inorder: HDBEAFCG · preorder: ABDHECFG · postorder: HDEBFGCA
- Traverse the tree (in any order), append each node to the end of its level's list, then print the lists in turn.
- Each item is handled 3 times → 3n = O(n) time; memory O(n + h) (lg n ≤ h ≤ n).
Other Routines
Method II: level-order traversal with a queue
- To print level by level, first in must be first out: a node's children are printed after the other nodes on its level → a queue (FIFO).
- Enqueue the root; at each step dequeue a node from the front, print it, and enqueue its children at the rear.
- When the queue is empty (
dequeuereturns NULL), the traversal ends. The tree may be empty: start withif (!L) return; - The queue also holds the nodes' addresses (a circular queue).
void enqueue(int front, int *rear, tree_pointer p, tree_pointer q[]) { *rear = (*rear + 1) % MAX_SIZE; if (*rear == front) { /* full */ fprintf(stderr, "Queue is full\n"); exit(EXIT_FAILURE); } q[*rear] = p; } tree_pointer dequeue(int *front, int rear, tree_pointer q[]) { if (*front == rear) return NULL; /* empty */ *front = (*front + 1) % MAX_SIZE; return q[*front]; }
Other Routines · Run the code step by step
Level by level with a queue: A B C D E F G H
The root is enqueued (rear = 1). Circular queue: front points one before the first item.
A is dequeued from the front and printed (FIFO: first in, first out).
A's children (B, C) are enqueued at the rear: the next level waits its turn.
B is dequeued from the front and printed (FIFO: first in, first out).
B's children (D, E) are enqueued at the rear: the next level waits its turn.
C is dequeued from the front and printed (FIFO: first in, first out).
C's children (F, G) are enqueued at the rear: the next level waits its turn.
D is dequeued from the front and printed (FIFO: first in, first out).
D's child (H) is enqueued at the rear: the next level waits its turn.
E is dequeued from the front and printed (FIFO: first in, first out).
F is dequeued from the front and printed (FIFO: first in, first out).
G is dequeued from the front and printed (FIFO: first in, first out).
H is dequeued from the front and printed (FIFO: first in, first out).
The queue is empty (front == rear): dequeue returns NULL and the loop ends. Output, level by level: ABCDEFGH.
void level_order(tree_pointer L) { tree_pointer queue[MAX_SIZE]; int front = 0, rear = 0; if (!L) return; // tree may be empty enqueue(front, &rear, L, queue); while ((L = dequeue(&front, rear, queue))) { printf("%c", L->data); if (L->left_child) enqueue(front, &rear, L->left_child, queue); if (L->right_child) enqueue(front, &rear, L->right_child, queue); } }
Other Routines
The cost of level-order traversal
- Each node enters and leaves the queue once: 2n = O(n) time.
- The queue holds at most about one level's width (w) of nodes (plus a few from the next).
- Complete tree: last level ≈ n/2 nodes → O(n) memory; skewed tree: O(1).
- The O(lg n) memory bound is for stack-based depth-first traversals (balanced tree), not for level order.
- On graphs this is breadth-first search (BFS); with a stack instead of a queue it becomes DFS.
| traversal | helper structure | extra memory |
|---|---|---|
| preorder/inorder/postorder | stack (LIFO) | O(h) |
| level by level | queue (FIFO) | O(w) ≤ O(n) |
Other Routines
QUESTION: make a copy of a tree
tree_pointer copy(tree_pointer L) {
if (!L) return NULL;
tree_pointer T = malloc(sizeof *T);
if (!T) { perror("malloc"); exit(1); }
T->left_child = copy(L->left_child);
T->right_child = copy(L->right_child);
T->data = L->data;
return T;
}- The data is written after both children are copied: the routine traverses the tree in postorder.
- Moving the lines around easily turns it into preorder or inorder.
- Plain
mallocwith a check is used here instead ofget_node().
Other Routines · Run the code step by step
copy(): the original tree and its copy
A new node is allocated for A (malloc checked); its data isn't written yet.
A new node is allocated for B (malloc checked); its data isn't written yet.
L is NULL → nothing to copy, return NULL (B's left copy will be NULL).
The left call returned → T->left_child = NULL.
L is NULL → nothing to copy, return NULL (B's right copy will be NULL).
The right call returned → T->right_child = NULL.
The data (B) is copied and the new node's address is returned to the caller.
The left call returned → T->left_child = clone(B).
A new node is allocated for C (malloc checked); its data isn't written yet.
L is NULL → nothing to copy, return NULL (C's left copy will be NULL).
The left call returned → T->left_child = NULL.
L is NULL → nothing to copy, return NULL (C's right copy will be NULL).
The right call returned → T->right_child = NULL.
The data (C) is copied and the new node's address is returned to the caller.
The right call returned → T->right_child = clone(C).
The data (A) is copied and the new node's address is returned to the caller.
tree_pointer copy(tree_pointer L) {
if (!L) return NULL;
tree_pointer T = malloc(sizeof *T);
if (!T) { perror("malloc"); exit(1); }
T->left_child = copy(L->left_child);
T->right_child = copy(L->right_child);
T->data = L->data;
return T;
}Other Routines
QUESTION: are two trees equivalent (isomorphic)?
int equal(tree_pointer L, tree_pointer T) { return (!L && !T) || (L && T && L->data == T->data && equal(L->left_child, T->left_child) && equal(L->right_child, T->right_child)); }
If only shape similarity matters (not the data), drop L->data == T->data.
- Two empty trees are equal; an empty and a non-empty tree are not.
- If both are non-empty: the roots are equal and the left subtrees are equal and the right subtrees are equal.
&&and||short-circuit: the recursion stops at the first difference.
Other Routines · Run the code step by step
equal(): A(B,C) vs. A(B,D)
Both non-empty and the data match (A = A) → compare the left subtrees.
Both non-empty and the data match (B = B) → compare the left subtrees.
Both NULL: (!L && !T) is true → 1 (empty trees are equal); the right side of || is never evaluated.
B: the left subtrees are equal → compare the right subtrees.
Both NULL: (!L && !T) is true → 1 (empty trees are equal); the right side of || is never evaluated.
B: the right side returned 1 → this call returns 1.
A: the left subtrees are equal → compare the right subtrees.
The data differ (C ≠ D) → && short-circuits; returns 0 without looking at the subtrees.
A: the right side returned 0 → this call returns 0.
int equal(tree_pointer L, tree_pointer T) { return (!L && !T) || (L && T && L->data == T->data && equal(L->left_child, T->left_child) && equal(L->right_child, T->right_child)); }
Other Routines
QUESTION: write equal() a different way
int equal2(tree_pointer L, tree_pointer T) { if (L == NULL || T == NULL) return L == T; /* both NULL? */ if (L->data != T->data) return 0; if (!equal2(L->left_child, T->left_child)) return 0; return equal2(L->right_child, T->right_child); }
- Early returns (guards) instead of a single
returnexpression; the behavior is the same. L == T: when one is NULL, true only if both are NULL.- The return value of every recursive call must be used.
Other Routines · Run the code step by step
QUESTION: swap the left and right children
A: the left (B) and right (C) pointers are swapped; the data stays put.
C: the left (NULL) and right (NULL) pointers are swapped; the data stays put.
L is NULL → return without doing anything.
L is NULL → return without doing anything.
B: the left (D) and right (NULL) pointers are swapped; the data stays put.
L is NULL → return without doing anything.
D: the left (NULL) and right (NULL) pointers are swapped; the data stays put.
L is NULL → return without doing anything.
L is NULL → return without doing anything.
Done: the tree is now its mirror image (the inorder sequence is reversed: CABD).
#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t)) void swap_children(tree_pointer L) { tree_pointer p; if (L) { SWAP(L->left_child, L->right_child, p); swap_children(L->left_child); swap_children(L->right_child); } }
“I'm not changing the data, just swapping the pointers.”
Other Routines
SWAP before, between, or after the recursive calls
Example tree: every right subtree is a single branch. SWAP before the calls: every node is swapped, giving a left-skewed mirror.
SWAP at the end (postorder) gives the same result. Between the calls, though: the left (NULL) is processed, the swap happens, then the “right” (now NULL) is processed → the B subtree is never touched.
The “same result” observation holds for before and after; in the middle the result differs.
Exam Question
Exam question: inorder + postorder → tree
Draw the binary tree whose inorder sequence is C M D A K N B F E G and whose postorder sequence is D A N F E B K M G C. There is exactly one such tree.
Solution (step by step)
The last in postorder is C → the root is C. Nothing precedes C in inorder → C has no left child.
The last of the remaining in postorder is G → C's right child. Nothing follows G in inorder → G has no right child.
Next is M. Nothing precedes M in inorder (within this subtree) → M's left is empty; M is G's left child.
Next is K, M's right child. D and A precede K in inorder → D and A are in K's left subtree.
Of D and A, A comes later in postorder → A is the ancestor (K's left child).
D is printed before A in inorder, so it is A's left child.
K's right subtree: N, B, F, E. The last of these in postorder is B → K's right child is B.
N precedes B in inorder → N is B's left child.
Next is E; it goes to B's right.
The last node is F: it is left of E in inorder → E's left child. The tree is complete and unique.
Method: read the postorder sequence from back to front (each letter is the root of a subtree); inorder splits that letter's left and right sides. Preorder + inorder also determines a unique tree; preorder + postorder generally does not (you can't tell whether a single child is on the left or the right).
Lab · C code step by step
Lab: Tree Traversals
Summary
Complexity summary (n nodes, depth h)
| operation | time | extra memory | note |
|---|---|---|---|
| parent / child (array representation) | O(1) | 2k−1 cells | no waste for a complete tree |
| recursive preorder / inorder / postorder | O(n) | O(h) | n+1 calls on NULL |
| stack-based inorder / preorder / postorder | O(n) | O(h) | addresses go on the stack |
| level by level (queue) | O(n) | O(w) ≤ O(n) | w: the widest level |
| print leaves, Q7–9 | O(n) | O(h) | traversal + condition |
| copy | O(n) | O(h) + n nodes | postorder |
| equal | O(min(n₁, n₂)) | O(h) | stops at the first difference |
| swap_children | O(n) | O(h) | pointers only |
h: lg n ≤ h ≤ n (balanced ↔ skewed). In this course depth is measured in levels.
Summary
Common mistakes
L->data without a NULL check (“the tree pointer can come in as NULL”).return.|| instead of && in the leaf condition.Summary
Exercises
- Prove that n0 = n2 + 1.
- Draw the expression tree for
(A+B)*(C-D)and write its three traversals. - Write
int count(tree_pointer L), which returns the number of nodes. - Draw the tree whose preorder is
A B D E C Fand whose inorder isD B E A F C. - Write a queue-based routine that prints each level right to left.
- Write a routine that checks whether two trees are mirror images of each other.
Hints / answers
- n = n0+n1+n2; every node except the root has one incoming edge: n−1 = n1+2n2. Subtract one equation from the other.
- preorder
*+AB-CD, inorderA+B*C-D, postorderAB+CD-*. return L ? 1 + count(L->left_child) + count(L->right_child) : 0;- A is the root; left B(D, E); right C(F, –).
- Enqueue the right child first, then the left.
- In
equal, compare L's left with T's right and L's right with T's left.
Summary
Chapter summary
Root, parent, child, sibling, ancestor, descendant, degree, leaf; levels start at 1, depth = the largest level.
≤ 2i−1 nodes on level i, ≤ 2k−1 nodes at depth k; a complete tree fits in an array.
Complete and fixed tree → array; changing tree → tree_pointer links.
The three recursive traversals share one skeleton; iterative with a stack, level by level with a queue.
Leaves, copy, equal, swap_children: all follow the “traverse + process” pattern.
O(n) time; O(h) memory, proportional to the depth.
Summary
References and next steps
- E. Horowitz, S. Sahni, S. Anderson-Freed, Fundamentals of Data Structures in C, 2nd ed., Chapter 5 (Trees).
- T. H. Cormen et al., Introduction to Algorithms, Appendix B.5 and Chapter 12.
- R. Sedgewick, Algorithms in C, Parts 1–4, Chapter 5 (Trees).
Coming next: binary search trees and threaded binary trees.