Before Class: Read sections 9.2.2-9.2.6 in the text.
Goals: This laboratory exercise provides some experience using a binary search tree structure.
Discussion: As noted in the text, a binary search tree is a tree, in which
In addition, it is convenient for an external pointer to designate a cons cell -- as every other list node also is specified from a cons cell. As an example, the following logical tree
As a list, this might be represented as:
((5
(2
(3 () ())
())
(8
()
(11 () ()))
))
~walker/153/labs/bst.ss contains code for a simple
binary-search tree class, with implemented operations empty?,
insert!, and print-all. The bst class also has
unimplemented operations for count, find and
print-leaves.
(load "~walker/153/labs/bst.ss") (define maple (bst)) (maple 'empty?) (maple 'insert! 123) (maple 'empty?) (maple 'insert! 37) (maple 'insert! 23) (maple 'insert! 48) (maple 'insert! 96) (maple 'insert! 285) (maple 'insert! 185) (maple 'insert! 200) (maple 'insert! 309) (maple 'print-all) (maple 'find 48) (maple 'count) (maple 'print-leaves)
insert! procedure moves down the tree, moving left or
right as dictated by the value of a new item, until it reaches the bottom
of the tree. When a null position is found, a new node is created to
insert a new node containing the new value.
find operation.
print-all procedure displays data from all nodes in the
tree by recursively printing, for each node, the left subtree, the data at
the node, and the right subtree. This is called an in-order
traversal of the tree. For this procedure, spacing is added to
indicate various levels of data within the tree. An asterisk * is printed
at each null tree.
print-all to fill in the details for the
print-leaves operation, which prints just the leaves within a
tree. Here, one can still traverse the full tree -- but printing should
occur only if a node has only null left and right subtrees.
print-all also can be used to count the number of
(non null) nodes in a tree. Complete the details of the count
operation.
height which computes the height of a tree.
This document is available on the World Wide Web as
http://www.math.grin.edu/~walker/courses/153/lab-bst.html