Chapter 10: Trees

Data Structures and Algorithms with C
TerminologyBinary treesArray / linked representationRecursive traversalsIterative traversalsLevel order, copy, equality
Source: Horowitz–Sahni–Anderson-Freed, Chapter 5

Introduction

Learning Outcomes

Use the terminology

Point out root, parent, child, sibling, ancestor, descendant, degree, level, depth, and leaf on a tree.

Analyze binary trees

Prove the lemma (2i−1, 2k−1); tell perfect, complete, and incomplete trees apart.

Build both representations

Represent trees with an array (parent = ⌊i/2⌋) and with links (tree_pointer); compare their memory cost.

Traversal

Write preorder, inorder, and postorder recursively and iteratively with a stack; traverse level by level.

Write tree routines

Build recursive routines for printing leaves, copying, equivalence, and swapping left and right.

Work out the cost

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.
treeABCDEgraph (not a tree)ABCDD has two parents

Terminology

Terminology on an example tree

level 1level 2level 3level 4A3B2EKLF0CGD3HMIJ
Parent / child / sibling

B is the parent of E and F; E and F are B's children. Children of the same parent are siblings.

Degree

The number of subtrees of a node: A has degree 3, F degree 0 (the small numbers at the upper right).

Leaf / terminal node

A node of degree 0: K, L, F, G, M, I, J.

Terminology

Terminology step by step

level 1level 2level 3level 4ABEKLFCGDHMIJRoot: the only node with no parent → A

The root is A. Levels are numbered from the root: in this course the root is at level 1.

level 1level 2level 3level 4ABEKLFCGDHMIJB is the parent of E and F; E and F are siblings

A node with subtrees is the parent of their roots, and they are its children.

level 1level 2level 3level 4ABEKLFCGDHMIJB, C, D are siblings (their parent is A)

Children of the same parent are siblings. The family terms extend to other generations: grandparent, grandchild.

level 1level 2level 3level 4ABEKLFCGDHMIJM's ancestors: A, D, H (the path from the root to M)

The ancestors of a node are all the nodes on the path from the root to it. D is M's grandparent.

level 1level 2level 3level 4ABEKLFCGDHMIJB's descendants: E, F, K, L

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.

level 1level 2level 3level 4ABEKLFCGDHMIJLeaves (degree 0): K, L, F, G, M, I, J

Nodes of degree 0 are called leaves or terminal nodes.

level 1level 2level 3level 4A3BEKLFCGD3HMIJDegree of the tree = 3 · depth = 4 levels

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.
conceptthis courseCLRS
level of the root10
level of M43
depth of the tree4height 3
empty tree0−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.
ABCDABDHIECFJGKskewed lefta binary tree with 4 levels

Binary Trees

Lemma: the maximum number of nodes on a level and in a tree

level 1: 2^0 = 1level 2: —level 3: —level 4: —total = 2^1 − 1 = 1

i) The maximum number of nodes on level i is 2i−1 (i ≥ 1). Base: for i = 1, 20 = 1 (the root alone).

level 1: 2^0 = 1level 2: 2^1 = 2level 3: —level 4: —total = 2^2 − 1 = 3

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.

level 1: 2^0 = 1level 2: 2^1 = 2level 3: 2^2 = 4level 4: —total = 2^3 − 1 = 7

ii) A binary tree of depth k has at most 2k − 1 nodes: Σi=1..k 2i−1 = 20 + 21 + … + 2k−1.

level 1: 2^0 = 1level 2: 2^1 = 2level 3: 2^2 = 4level 4: 2^3 = 8total = 2^4 − 1 = 15

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

1234567891012345678911perfect: 2^4 − 1 = 15complete: 1..10 with no gapsnot complete: node 10 is missing!
DEFINITION: Perfect

A binary tree of depth k with 2k − 1 nodes: every level is full.

DEFINITION: Complete

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.

Why does it matter?

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).
ABDHIECFJGKn = 11: n0 = 5 leaves, n1 = 2, n2 = 4 → 5 = 4 + 1

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

ABCDEFGHI1A2B3C4D5E6F7G8H9I9 cells allocated, all 9 in use: no wasteparent(9) = ⌊9/2⌋ = 4 → D; left(4) = 8 → H

Complete tree: almost every cell of the array is filled; little or no memory is wasted.

A1B2C4D8E161A2B3·4C5·6·7·8D9·…15·16E17·…31·depth 5 → 2^5 − 1 = 31 cells; only 5 in use“That's not an array! That's a tree!”

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.

Instructor “Storage and access are the two main topics of computer science. … If our tree is a complete binary tree and there will be no insertions or deletions, implementing it with an array is a good fit.”

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).
ABCDEdark box = NULLleft child | data | right child

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);
}
Here 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 parent field if needed).
Rule of thumb: if the tree is complete and fixed, use an array (e.g. a heap); if its shape changes, use links.

Representation

Turning a general tree into a binary tree: left child, right sibling

ABEKLFCGDHMIJ

In a general tree the number of children varies from node to node; it is hard to hold with a fixed-field struct.

ABEKLFCGDHMIJorange: first child (left) · dashed: sibling (right)

Each node keeps a link only to its first child; siblings are chained together through a right sibling link.

ABEKLFCGDHMIJ

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.
ordername
1Left – Data – Rightinorder
2Left – Right – Datapostorder
3Data – Left – Rightpreorder
4Right – Data – Leftreverse inorder
5Right – Left – Datareverse postorder
6Data – Right – Leftreverse preorder

Traversals

An arithmetic expression tree and three notations

+**/ABCDE
  • 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

A1B2C3D4G5H6E7I8J9K10F11L12preorderABCDGHEIJKFLsmall numbers: visit order

Preorder (V-L-R): the root first, then the whole left subtree, then the right subtree → ABCDGHEIJKFL

A10B1C5D3G2H4E6I8J7K9F12L11inorderBGDHCEJIKALFsmall numbers: visit order

Inorder (L-V-R): B's left is empty, so B is printed first → BGDHCEJIKALF

A12B9C8D3G1H2E7I6J4K5F11L10postorderGHDJKIECBLFAsmall numbers: visit order

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);
  }
}
Instructor “NOTE: the tree pointer can come in as NULL, and nobody pays any attention to that!”

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)

ABDCrunning nowon the call stackprintednot printed yet

L = A: call inorder(B) for the left subtree; this frame waits.

ABDCrunning nowon the call stackprintednot printed yet

L = B: call inorder(D) for the left subtree; this frame waits.

ABDCrunning nowon the call stackprintednot printed yet

L = D: call inorder(NULL) for the left subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (D has no left child).

ABDCrunning nowon the call stackprintednot printed yet

L = D: the left subtree is done; now print the root → D is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = D: call inorder(NULL) for the right subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (D has no right child).

ABDCrunning nowon the call stackprintednot printed yet

L = B: the left subtree is done; now print the root → B is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = B: call inorder(NULL) for the right subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (B has no right child).

ABDCrunning nowon the call stackprintednot printed yet

L = A: the left subtree is done; now print the root → A is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = A: call inorder(C) for the right subtree; this frame waits.

ABDCrunning nowon the call stackprintednot printed yet

L = C: call inorder(NULL) for the left subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (C has no left child).

ABDCrunning nowon the call stackprintednot printed yet

L = C: the left subtree is done; now print the root → C is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = C: call inorder(NULL) for the right subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (C has no right child).

ABDCrunning nowon the call stackprintednot printed yet

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

ABDCrunning nowon the call stackprintednot printed yet

L = A: preorder prints itself first → A is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = A: call preorder(B) for the left subtree; this frame waits.

ABDCrunning nowon the call stackprintednot printed yet

L = B: preorder prints itself first → B is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = B: call preorder(D) for the left subtree; this frame waits.

ABDCrunning nowon the call stackprintednot printed yet

L = D: preorder prints itself first → D is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = D: call preorder(NULL) for the left subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (D has no left child).

ABDCrunning nowon the call stackprintednot printed yet

L = D: call preorder(NULL) for the right subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (D has no right child).

ABDCrunning nowon the call stackprintednot printed yet

L = B: call preorder(NULL) for the right subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (B has no right child).

ABDCrunning nowon the call stackprintednot printed yet

L = A: call preorder(C) for the right subtree; this frame waits.

ABDCrunning nowon the call stackprintednot printed yet

L = C: preorder prints itself first → C is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = C: call preorder(NULL) for the left subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (C has no left child).

ABDCrunning nowon the call stackprintednot printed yet

L = C: call preorder(NULL) for the right subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (C has no right child).

ABDCrunning nowon the call stackprintednot printed yet

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

ABDCrunning nowon the call stackprintednot printed yet

L = A: call postorder(B) for the left subtree; this frame waits.

ABDCrunning nowon the call stackprintednot printed yet

L = B: call postorder(D) for the left subtree; this frame waits.

ABDCrunning nowon the call stackprintednot printed yet

L = D: call postorder(NULL) for the left subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (D has no left child).

ABDCrunning nowon the call stackprintednot printed yet

L = D: call postorder(NULL) for the right subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (D has no right child).

ABDCrunning nowon the call stackprintednot printed yet

L = D: both subtrees are done; the root is printed last → D is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = B: call postorder(NULL) for the right subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (B has no right child).

ABDCrunning nowon the call stackprintednot printed yet

L = B: both subtrees are done; the root is printed last → B is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = A: call postorder(C) for the right subtree; this frame waits.

ABDCrunning nowon the call stackprintednot printed yet

L = C: call postorder(NULL) for the left subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (C has no left child).

ABDCrunning nowon the call stackprintednot printed yet

L = C: call postorder(NULL) for the right subtree; this frame waits.

ABDCNULLrunning nowon the call stackprintednot printed yet

L == NULL → if (L) is false; the call returns without doing anything (C has no right child).

ABDCrunning nowon the call stackprintednot printed yet

L = C: both subtrees are done; the root is printed last → C is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

L = A: both subtrees are done; the root is printed last → A is added to the output.

ABDCrunning nowon the call stackprintednot printed yet

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).

Instructor “Claims like ‘Professor, recursive algorithms use a lot of memory’ are just an excuse not to write recursive code.”
Instructor “We don't walk away once the algorithm is written. In computer science we have to analyze it.”

Traversals

You learn recursive code by writing it yourself

Instructor “If I put all my past questions online, that would be misleading. I could watch Naim Süleymanoğlu lift a barbell 100 times and I still couldn't lift it. You have to focus on the question ‘how was this written?’”
Instructor “If this algorithm still isn't clear, drawing the tree of stack frames will help.”
I hear and I forget, I see and I remember, I do and I understand.

— Chinese proverb

The call tree

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

+*/8435(8 / 4) * 3 + 5running now=value returned

+ is an operator: evaluate the left subexpression first.

+*/8435(8 / 4) * 3 + 5running now=value returned

* is an operator: evaluate the left subexpression first.

+*/8435(8 / 4) * 3 + 5running now=value returned

/ is an operator: evaluate the left subexpression first.

+*/8=8435(8 / 4) * 3 + 5running now=value returned

8 is a leaf: it returns its number → 8.

+*/8=8435(8 / 4) * 3 + 5running now=value returned

Left value a = 8. Now evaluate the right subexpression.

+*/8=84=435(8 / 4) * 3 + 5running now=value returned

4 is a leaf: it returns its number → 4.

+*/=28=84=435(8 / 4) * 3 + 5running now=value returned

b = 4; 8 / 4 = 2 is returned (postorder: left, right, root).

+*/=28=84=435(8 / 4) * 3 + 5running now=value returned

Left value a = 2. Now evaluate the right subexpression.

+*/=28=84=43=35(8 / 4) * 3 + 5running now=value returned

3 is a leaf: it returns its number → 3.

+*=6/=28=84=43=35(8 / 4) * 3 + 5running now=value returned

b = 3; 2 * 3 = 6 is returned (postorder: left, right, root).

+*=6/=28=84=43=35(8 / 4) * 3 + 5running now=value returned

Left value a = 6. Now evaluate the right subexpression.

+*=6/=28=84=43=35=5(8 / 4) * 3 + 5running now=value returned

5 is a leaf: it returns its number → 5.

+=11*=6/=28=84=43=35=5(8 / 4) * 3 + 5running now=value returned

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.
Instructor “So when we line the nodes up, we want to reach the one we added last first. Well, that's a stack! How elegantly we've explained it!”

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)

ABDECLstack0A123◀ top=0

Push A (its address!), then go left: L = A->left_child = B.

ABDECLstack0A1B23◀ top=1

Push B (its address!), then go left: L = B->left_child = D.

ABDECLstack0A1B2D3◀ top=2

Push D (its address!), then go left: L = D->left_child = NULL. L is NULL → the inner loop ends.

ABDECLstack0A1B23◀ top=1

Pop D; its left side is done → print D.

ABDECstack0A1B23◀ top=1L = NULL

L = D->right_child = NULL: no right subtree, continue from the stack.

ABDECLstack0A123◀ top=0

Pop B; its left side is done → print B.

ABDECLstack0A123◀ top=0

L = B->right_child = E: the right subtree is traversed the same way.

ABDECLstack0A1E23◀ top=1

Push E (its address!), then go left: L = E->left_child = NULL. L is NULL → the inner loop ends.

ABDECLstack0A123◀ top=0

Pop E; its left side is done → print E.

ABDECstack0A123◀ top=0L = NULL

L = E->right_child = NULL: no right subtree, continue from the stack.

ABDECLstack0123top=−1 (empty)

Pop A; its left side is done → print A.

ABDECLstack0123top=−1 (empty)

L = A->right_child = C: the right subtree is traversed the same way.

ABDECLstack0C123◀ top=0

Push C (its address!), then go left: L = C->left_child = NULL. L is NULL → the inner loop ends.

ABDECLstack0123top=−1 (empty)

Pop C; its left side is done → print C.

ABDECstack0123top=−1 (empty)L = NULL

L = C->right_child = NULL: no right subtree, continue from the stack.

ABDECstack0123top=−1 (empty)L = NULL

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 &&.
Instructor “Our goal in this course isn't to build large automation systems, but to write small modules masterfully. Write small pieces of code many times, in many different ways.”
“Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it.”

— Alan J. Perlis

Iterative Traversal

Questions: write it by changing the traversal pattern

  1. Write the preorder traversal iteratively.
  2. Write the postorder traversal iteratively. (This one is harder.)
  3. A recursive routine that prints the leaves left to right.
  4. A recursive routine that prints the leaves right to left.
  5. An iterative routine that prints the leaves left to right.
  6. An iterative routine that prints the leaves right to left.
  7. A recursive routine that prints the nodes with only a left child.
  8. A recursive routine that prints the nodes with only a right child.
  9. A recursive routine that prints the nodes with both children.
They all reduce to one of two patterns: recursive traversal + conditional printf or stack-based traversal + conditional printf. For “right to left,” swap 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 printf happens 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).
O(n) time: each node is pushed once, popped once, and examined at the top at most twice. O(h) memory.

Iterative Traversal · Run the code step by step

Q2 step by step: A(B(D),C)

ABDCLstack0A12◀ top=0

Push L = A and go left: L = B.

ABDCLstack0A1B2◀ top=1

Push L = B and go left: L = D.

ABDCstack0A1B2D◀ top=2

Push L = D and go left: L = NULL.

ABDCstack0A1B2◀ top=1

Top is D: no right child → print D and pop it; last = D.

ABDCstack0A12◀ top=0

Top is B: no right child → print B and pop it; last = B.

ABDCLstack0A12◀ top=0

Top is A: its right child C exists and hasn't been printed → right subtree first (L = C).

ABDCstack0A1C2◀ top=1

Push L = C and go left: L = NULL.

ABDCstack0A12◀ top=0

Top is C: no right child → print C and pop it; last = C.

ABDCstack012top=−1 (empty)

Top is A: its right child C was just printed (last) → print A and pop it; last = A.

ABDCstack012top=−1 (empty)

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).

The common pattern: “traverse the tree and print when the condition holds.” !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

ABDHECFG

inorder: HDBEAFCG · preorder: ABDHECFG · postorder: HDEBFGCA

1A2BC3DEFG4H
  • 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 (dequeue returns NULL), the traversal ends. The tree may be empty: start with if (!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

ABDHECFGL0·1A2·3·4·5·6·7·8·▲front▲rear

The root is enqueued (rear = 1). Circular queue: front points one before the first item.

ABDHECFGL0·1A2·3·4·5·6·7·8·▲front▲rear

A is dequeued from the front and printed (FIFO: first in, first out).

ABDHECFGL0·1A2B3C4·5·6·7·8·▲front▲rear

A's children (B, C) are enqueued at the rear: the next level waits its turn.

ABDHECFGL0·1A2B3C4·5·6·7·8·▲front▲rear

B is dequeued from the front and printed (FIFO: first in, first out).

ABDHECFGL0·1A2B3C4D5E6·7·8·▲front▲rear

B's children (D, E) are enqueued at the rear: the next level waits its turn.

ABDHECFGL0·1A2B3C4D5E6·7·8·▲front▲rear

C is dequeued from the front and printed (FIFO: first in, first out).

ABDHECFGL0·1A2B3C4D5E6F7G8·▲front▲rear

C's children (F, G) are enqueued at the rear: the next level waits its turn.

ABDHECFGL0·1A2B3C4D5E6F7G8·▲front▲rear

D is dequeued from the front and printed (FIFO: first in, first out).

ABDHECFGL0·1A2B3C4D5E6F7G8H▲front▲rear

D's child (H) is enqueued at the rear: the next level waits its turn.

ABDHECFGL0·1A2B3C4D5E6F7G8H▲front▲rear

E is dequeued from the front and printed (FIFO: first in, first out).

ABDHECFGL0·1A2B3C4D5E6F7G8H▲front▲rear

F is dequeued from the front and printed (FIFO: first in, first out).

ABDHECFGL0·1A2B3C4D5E6F7G8H▲front▲rear

G is dequeued from the front and printed (FIFO: first in, first out).

ABDHECFGL0·1A2B3C4D5E6F7G8H▲front▲rear

H is dequeued from the front and printed (FIFO: first in, first out).

ABDHECFG0·1A2B3C4D5E6F7G8H▲front▲rear

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.
traversalhelper structureextra memory
preorder/inorder/postorderstack (LIFO)O(h)
level by levelqueue (FIFO)O(w) ≤ O(n)
Instructor “Depth-first search, by its nature, needed a stack; this problem needs a queue.”

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;
}
Instructor “First do on paper what I did on the board, and see that it is solved recursively. This routine works bottom-up; it could have been written top-down too.”
  • 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 malloc with a check is used here instead of get_node().

Other Routines · Run the code step by step

copy(): the original tree and its copy

L (original)T (clone)ABC?

A new node is allocated for A (malloc checked); its data isn't written yet.

L (original)T (clone)ABC??

A new node is allocated for B (malloc checked); its data isn't written yet.

L (original)T (clone)ABCNULL??

L is NULL → nothing to copy, return NULL (B's left copy will be NULL).

L (original)T (clone)ABC??

The left call returned → T->left_child = NULL.

L (original)T (clone)ABCNULL??

L is NULL → nothing to copy, return NULL (B's right copy will be NULL).

L (original)T (clone)ABC??

The right call returned → T->right_child = NULL.

L (original)T (clone)ABC?B

The data (B) is copied and the new node's address is returned to the caller.

L (original)T (clone)ABC?B

The left call returned → T->left_child = clone(B).

L (original)T (clone)ABC?B?

A new node is allocated for C (malloc checked); its data isn't written yet.

L (original)T (clone)ABCNULL?B?

L is NULL → nothing to copy, return NULL (C's left copy will be NULL).

L (original)T (clone)ABC?B?

The left call returned → T->left_child = NULL.

L (original)T (clone)ABCNULL?B?

L is NULL → nothing to copy, return NULL (C's right copy will be NULL).

L (original)T (clone)ABC?B?

The right call returned → T->right_child = NULL.

L (original)T (clone)ABC?BC

The data (C) is copied and the new node's address is returned to the caller.

L (original)T (clone)ABC?BC

The right call returned → T->right_child = clone(C).

L (original)T (clone)ABCABC

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.
Instructor “Checking whether two binary trees are isomorphic is this easy! Deciding whether two graphs are isomorphic, on the other hand, is quite a hard problem.”

Other Routines · Run the code step by step

equal(): A(B,C) vs. A(B,D)

LTABCABD

Both non-empty and the data match (A = A) → compare the left subtrees.

LTABCABD

Both non-empty and the data match (B = B) → compare the left subtrees.

LTABCABD

Both NULL: (!L && !T) is true → 1 (empty trees are equal); the right side of || is never evaluated.

LTABCABD

B: the left subtrees are equal → compare the right subtrees.

LTABCABD

Both NULL: (!L && !T) is true → 1 (empty trees are equal); the right side of || is never evaluated.

LTABCABD

B: the right side returned 1 → this call returns 1.

LTABCABD

A: the left subtrees are equal → compare the right subtrees.

LTABCABD

The data differ (C ≠ D) → && short-circuits; returns 0 without looking at the subtrees.

LTABCABD

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 return expression; 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.
Instructor “‘Professor, mine runs beautifully, it just never comes back. I call and call, but it doesn't return, it gets stuck.’ Then we still haven't learned to write recursive algorithms.”

Other Routines · Run the code step by step

QUESTION: swap the left and right children

ACBDrunning nowchildren swappedwaiting on the stack

A: the left (B) and right (C) pointers are swapped; the data stays put.

ACBDrunning nowchildren swappedwaiting on the stack

C: the left (NULL) and right (NULL) pointers are swapped; the data stays put.

ACBDNULLrunning nowchildren swappedwaiting on the stack

L is NULL → return without doing anything.

ACBDNULLrunning nowchildren swappedwaiting on the stack

L is NULL → return without doing anything.

ACBDrunning nowchildren swappedwaiting on the stack

B: the left (D) and right (NULL) pointers are swapped; the data stays put.

ACBDNULLrunning nowchildren swappedwaiting on the stack

L is NULL → return without doing anything.

ACBDrunning nowchildren swappedwaiting on the stack

D: the left (NULL) and right (NULL) pointers are swapped; the data stays put.

ACBDNULLrunning nowchildren swappedwaiting on the stack

L is NULL → return without doing anything.

ACBDNULLrunning nowchildren swappedwaiting on the stack

L is NULL → return without doing anything.

ACBDrunning nowchildren swappedwaiting on the stack

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

ABCDstart: right-skewed A-B-C-D
ABCDSWAP before → full mirror

Example tree: every right subtree is a single branch. SWAP before the calls: every node is swapped, giving a left-skewed mirror.

ABCDSWAP after → full mirror again
ABCDSWAP between → only the root swapped

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)
Cinorder:postorder:CMDAKNBFEGDANFEBKMGCSTEP 1

The last in postorder is C → the root is C. Nothing precedes C in inorder → C has no left child.

CGinorder:postorder:CMDAKNBFEGDANFEBKMGCSTEP 2

The last of the remaining in postorder is G → C's right child. Nothing follows G in inorder → G has no right child.

CGMinorder:postorder:CMDAKNBFEGDANFEBKMGCSTEP 3

Next is M. Nothing precedes M in inorder (within this subtree) → M's left is empty; M is G's left child.

CGMKinorder:postorder:CMDAKNBFEGDANFEBKMGCSTEP 4

Next is K, M's right child. D and A precede K in inorder → D and A are in K's left subtree.

CGMKAinorder:postorder:CMDAKNBFEGDANFEBKMGCSTEP 5

Of D and A, A comes later in postorder → A is the ancestor (K's left child).

CGMKADinorder:postorder:CMDAKNBFEGDANFEBKMGCSTEP 6

D is printed before A in inorder, so it is A's left child.

CGMKADBinorder:postorder:CMDAKNBFEGDANFEBKMGCSTEP 7

K's right subtree: N, B, F, E. The last of these in postorder is B → K's right child is B.

CGMKADBNinorder:postorder:CMDAKNBFEGDANFEBKMGCSTEP 8

N precedes B in inorder → N is B's left child.

CGMKADBNEinorder:postorder:CMDAKNBFEGDANFEBKMGCSTEP 9

Next is E; it goes to B's right.

CGMKADBNEFinorder:postorder:CMDAKNBFEGDANFEBKMGCSTEP 10

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)

operationtimeextra memorynote
parent / child (array representation)O(1)2k−1 cellsno waste for a complete tree
recursive preorder / inorder / postorderO(n)O(h)n+1 calls on NULL
stack-based inorder / preorder / postorderO(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–9O(n)O(h)traversal + condition
copyO(n)O(h) + n nodespostorder
equalO(min(n₁, n₂))O(h)stops at the first difference
swap_childrenO(n)O(h)pointers only

h: lg n ≤ h ≤ n (balanced ↔ skewed). In this course depth is measured in levels.

Summary

Common mistakes

1Accessing L->data without a NULL check (“the tree pointer can come in as NULL”).
2Starting the array representation at 0 while using the 1-based formulas (2i, 2i+1).
3Pushing a copy of the node onto the stack: isn't the address enough?
4Ignoring a recursive call's return value, or trying to do work after return.
5Writing || instead of && in the leaf condition.
6Mixing up degree and depth, or the level-1 and depth-0 conventions.

Summary

Exercises

  1. Prove that n0 = n2 + 1.
  2. Draw the expression tree for (A+B)*(C-D) and write its three traversals.
  3. Write int count(tree_pointer L), which returns the number of nodes.
  4. Draw the tree whose preorder is A B D E C F and whose inorder is D B E A F C.
  5. Write a queue-based routine that prints each level right to left.
  6. Write a routine that checks whether two trees are mirror images of each other.
Hints / answers
  1. n = n0+n1+n2; every node except the root has one incoming edge: n−1 = n1+2n2. Subtract one equation from the other.
  2. preorder *+AB-CD, inorder A+B*C-D, postorder AB+CD-*.
  3. return L ? 1 + count(L->left_child) + count(L->right_child) : 0;
  4. A is the root; left B(D, E); right C(F, –).
  5. Enqueue the right child first, then the left.
  6. In equal, compare L's left with T's right and L's right with T's left.

Summary

Chapter summary

Terminology

Root, parent, child, sibling, ancestor, descendant, degree, leaf; levels start at 1, depth = the largest level.

Binary trees

≤ 2i−1 nodes on level i, ≤ 2k−1 nodes at depth k; a complete tree fits in an array.

Representation

Complete and fixed tree → array; changing tree → tree_pointer links.

Traversal

The three recursive traversals share one skeleton; iterative with a stack, level by level with a queue.

Routines

Leaves, copy, equal, swap_children: all follow the “traverse + process” pattern.

Cost

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.

The End

Chapter 10: Trees
Next chapter: Chapter 11: Search Trees · Course page
1 / 1 Data Structures and Algorithms with C