These lecture notes are based on chapter 9 in ``Data Structures, Algorithms, & Software Principles in C'' by Thomas Standish.

Trees

Tree terminology comes from

tex2html_wrap25

Some basic definitions

Tree property: There is exactly one path from the root R to each descendant of R (note: there is only one root).

Lots of specialised trees

Binary Trees

most important kind - used to model yes/no, on/off, higher/lower, i.e., binary decisions

Recursive Definition: A binary tree is either the empty tree or a node that has left and right subtrees that are binary trees.

Empty trees are represented as boxes in the diagram below (but we will almost always omit the boxes).

tex2html_wrap27

Traversing Binary Trees

In the example tree from the previous diagram, the traversals will visit

Below is an example expression tree.

tex2html_wrap47

Linked Representation of Binary Trees

A typical tree structure in C

typedef struct node {
   value_type value;
   struct *node left;
   struct *node right;
} binary_tree_type;
Assumption is that empty trees will be null pointers.

Preorder traversal code, a recursive technique.

/* preorder traversal of a tree, a recursive technique */
void preorder(binary_tree_type *tree) {
  if (tree == NULL) return;
  visit(tree);
  preorder(tree->left);
  preorder(tree->right);
}

Preorder traversal code, a stack technique.

/* preorder traversal of a tree, implemented using a stack */
void preorder(binary_tree_type *tree) {
  stack_type *stack;

  stack = create_stack();
  push(tree, stack);
  while (!empty(stack)) {
    tree = pop(stack);
    visit(tree);
    push(tree->left, stack);
    push(tree->right, stack);
    }
}


Last updated Thu May 9 14:10:26 EST 1996.
Copyright © 1996. Curtis E. Dyreson and Olivier De Vel. All rights reserved.