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.


(defun flattenbt (tree) (flattenbtb tree '()) )
(defun flattenbtb (tree result)
  (if (consp tree)
      (flattenbtb (lhs tree)         ; 3. L child
                  (cons (op tree)    ; 2. parent
                        (flattenbtb
                          (rhs tree) ; 1. R child
                          result)))
      (if tree
          (cons tree result)
          result) ) )


>(flattenbt '(cat (bat ape
                       bee)
                  (elf dog
                       fox)))

(APE BAT BEE CAT DOG ELF FOX)