previous | index | next

Traversal Application: Drawing Trees

Drawing shapes, text, and lines in Racket/Scheme requires a "drawing context" and operations for manipulating it.

Without getting into details, suppose that we have the following procedures:

The following procedure employs a preorder traversal to draw an entire tree (although any traversal would suffice):
(define draw-tree
  (lambda (tree)
    (let ((dc ...)             ;; Set up a "drawing context" and determine the
	  (root-location ...)) ;; location of the root in the drawing area
      
      (define draw-tree-preorder
        (lambda (tree location)
          (draw-node tree location dc)
          (let ((left (left-subtree tree))
                (right (right-subtree tree)))
            (if (not (empty-tree? left))
                (begin
                  (draw-left-link tree location dc)
                  (draw-tree-preorder left 
                                      (left-child-location tree location))))
            (if (not (empty-tree? right))
                (begin
                  (draw-right-link tree location dc)
                  (draw-tree-preorder right
                                      (right-child-location tree location))))
          ))

      (draw-tree-preorder tree root-location))))

previous | index | next