Binary Tree Recursion

While recursion is not always the best method for linked lists, it usually is the best method for trees. We don't have a problem with stack depth because depth is only O(log(n)) if the tree is balanced.

Suppose that we want to add up all the numbers in a Lisp tree.


(defun addnums (tree)
  (if (consp tree)               ; interior node
      (+ (addnums (first tree))
         (addnums (rest tree)) )
      (if (numberp tree)         ; leaf node
          tree
          0) ) )

Suppose that we want the set of symbols in a Lisp tree.


(defun symbolset (tree)
  (if (consp tree)
      (union (symbolset (first tree))
             (symbolset (rest tree)) )
      (if (and tree (symbolp tree))
          (list tree)
          '()) ) )

Contents    Page-10    Prev    Next    Page+10    Index