Contents    Page-10    Prev    Next    Page+10    Index   

Flattening Binary Tree

An ordered binary tree can be flattened into an ordered list by a backwards inorder traversal. We do the inorder backwards so that pushing onto a stack (using cons) can be used to accumulate the result. This accumulation of a result in an extra variable is similar to tail recursion.


(defn flattenbtb [tree result]
  (if (cons? tree)          ; interior node
      (flattenbtb (lhs tree)         ; 3. L child
                  (cons (op tree)    ; 2. parent
                        (flattenbtb
                          (rhs tree) ; 1. R child
                          result)))
      (if (not (null? tree))
          (cons tree result)
          result) ) )

(defn flattenbt [tree] (flattenbtb tree '()) )