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.

(defn myfunb [tree answer]
         (if (interior? tree)
         (myfunb (right tree)
                  (myfunb (left tree) answer))
         (combine (baseanswer tree) answer)))

(defn myfun [tree] (myfunb tree init) )


; count numbers in a tree
(defn nnumsb [tree answer]
  (if (cons? tree)
      (nnumsb (rest tree)
              (nnumsb (first tree) answer))
      (if (number? tree)
          (+ 1 answer)
          answer) ) )
(defn nnums [tree] (nnumsb tree 0))