Contents    Page-10    Prev    Next    Page+10    Index   

Design Pattern: Nested Tree Recursion

Binary tree recursion can be written in a nested form, analogous to tail recursion. We carry the answer along, adding to it as we go. This form is useful if it is easier to combine an item with an answer than to combine two answers. Compare to p. btrdp

(defun myfun (tree) (myfunb tree init) )

(defun myfunb (tree answer)
         (if (interior? tree)
         (myfunb (right tree)
                  (myfunb (left tree) answer))
         (combine (baseanswer tree) answer)))


; count numbers in a tree
(defun nnums (tree) (nnumsb tree 0))
(defun nnumsb (tree answer)
  (if (consp tree)
      (nnumsb (rest tree)
              (nnumsb (first tree) answer))
      (if (numberp tree)
          (+ 1 answer)
          answer) ) )