Contents    Page-10    Prev    Next    Page+10    Index   

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 numbers in a Cons tree.

public static int addnums(Object tree) {
    if ( consp(tree) )  ; is this a Cons?
        return addnums(first((Cons)tree))
            +  addnums(rest((Cons)tree));
    else if ( numberp(tree) )
        return (int) (Integer) tree;
    else return 0;

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