Laboratory Exercises For Computer Science 153

An Introduction To Trees

An Introduction To Trees

Before Class: Read section 7.2 in the text.

Goals: This lab reviews elements of the tree data structure.

Discussion: A general tree is defined recursively as follows:

As noted in the text, I is called the root or root node, and each Ti is called a subtree of the tree. Nodes that have only null subtrees are called leaves or leaf nodes.

In Scheme, such a tree may be represented as the list:

(I  (T1)  (T2)  (T3)  ...  (Tn))
Since this definition is recursive, it may be applied multiple times to construct more complex trees, such as the one shown below:
A Simple Tree

In this example, e, k, l, m, n, h, o, p, and q are leaves (or trees with null subtrees); a is the root of the overall tree. f is the root of a tree with k and l as subtrees, etc. Similarly, b is the root of a tree with two subtrees, one containing e and one containing f, k, and l. In Scheme/list notation, the tree with b as root would be notated
(b (e) (f (k) (l)))
  1. Write the subtrees with roots c and d in Scheme/list notation.

  2. Answer exercises 7-9 and 7-10 from the text.

  3. In a file accompanying the textbook, the authors give the following definitions:
    (define t 
      '(1 (2 (3))
          (4 (7)
             (5 (6)))
          (10 (11 (12) (13))
              (19))))
    (define u 
      '(1 (2 (3))
          (4 (7)
             (5 (6)))
          (19 (11 (12) (13))
              (10))))
    
    Draw the tree structures corresponding to these list structures.

    What are the leaves of each tree?

Section 7.2 discusses the general format for processing within a tree structure. Review the algorithms and code given.
  1. Program 7-6 presents a procedure to print the nodes in a tree, using a letrec statement. Write a paragraph explaining how that program works.

  2. Rewrite Program 7-6 using a named-let expression.
    Test your code with trees t and u above.

  3. Could Program 7-6 be rewritten without recursion -- replacing the recursion in the letrec statement with a do statement?

  4. Assuming that all nodes in a non-empty tree contain numbers, write a procedure to find the sum of these numbers.
    Test your code with trees t and u above.

  5. Again, assuming that all nodes in a non-empty tree contain numbers, write a procedure to find the maximum of these values.
    Test your code with trees t and u above.

This document is available on the World Wide Web as

http://www.math.grin.edu/~walker/courses/153/lab-intro-trees.html

created April 18, 1998
last revised April 18, 1998