Trees are defined, some applications are presented, some computer representation strategies are considered, and tree traversal algorithms are discussed. Trees are file cabinets: good ways to store stuff. Once it's stored, however, we'll need to retrieve it; hence we must be able to efficiently traverse the tree checking what's in each file!
Definition: a tree is an acyclic, connected graph with one node designated as the root node.
"Because a tree is a connected graph, there is a path from the root to any other node in the tree; because the tree is acyclic, that path is unique [provided that no arc is used twice]." p. 364/371, Gersting.
The set of trees can also be defined recursively, as follows:
Example: Create a tree on a 4x6 card. Some of you should make rather ordered trees; others might think of very strange trees.
Use this tree terminology handout to classify your tree.
Exercise #2, p. 374/381.
Binary trees are special in that their children are classified as left or right. So in order to represent them, we need to specify left and right children for each node. Two representations are shown in Example 23, p. 367/375: a two-column array, and an adjacency list with three-field records.
Practice 20, p. 367/375.
We'll look at three tree traversal algorithms, which are represented recursively as follows:
Check out this animation showing how a tree is traversed by the three algorithms. (local copy)
Note the nice definitions of these traversal algorithms based on the recursive definition of a tree.
Exercise #18, p. 377/384.
Each traversal method has advantages in different situations. The example we consider is that of binary trees as representations of arithmetic expressions (e.g. Figure 5.40, p. 539/374).
``Why Did/Does HP Use RPN?
In the years that followed, computer scientists realized that RPN or postfix notation was very efficient for computer math. As a postfix expression is scanned from left to right, operands are simply placed into a last-in, first-out (LIFO) stack and operators may be immediately applied to the operands at the bottom of the stack. By contrast, expressions with parentheses and precedence (infix notation) require that operators be delayed until some later point. Thus, the compilers on on almost all modern computers converted statements to RPN for execution. (In fact, some computer manufacturers designed their computers around postfix notation.)'' (from the link above, on http://www.hpmuseum.org/rpn.htm)
Exercise #5, p. 374/381 (and write the expression in prefix and postfix notation).