Contents    Page-10    Prev    Next    Page+10    Index   

Design Pattern: Binary Tree Recursion

This pattern is like the one for lists, except that it calls itsefl twice for interior nodes. This is essentially the same as the divide-and-conquer design pattern.

(defn myfun [tree]
         (if (cons? tree)
                 (combine (myfun (first tree)) ; left
                         (myfun (rest tree))) ; right
                 (baseanswer tree) )) ; leaf node


(defn addnums [tree]
  (if (cons? tree)          ; interior node
      (+ (addnums (first tree))
         (addnums (rest tree)) )
      (if (number? tree)         ; leaf node
          tree
          0) ) )