Task

Implement a binary tree where each node carries an integer,   and implement:

   pre-order,
   in-order, 
   post-order,     and 
   level-order   traversal. 


Use those traversals to output the following tree:

         1
        / \
       /   \
      /     \
     2       3
    / \     /
   4   5   6
  /       / \
 7       8   9

The correct output should look like this:

preorder:    1 2 4 7 5 3 6 8 9
inorder:     7 4 2 5 1 8 6 9 3
postorder:   7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9



See also

   Wikipedia article:   Tree traversal.


(defn walk [node f order]
  (when node
   (doseq [o order]
     (if (= o :visit)
       (f (:val node))
       (walk (node o) f order)))))
 
(defn preorder [node f]
  (walk node f [:visit :left :right]))
 
(defn inorder [node f]
  (walk node f [:left :visit :right]))
 
(defn postorder [node f]
  (walk node f [:left :right :visit]))
 
(defn queue [& xs]
  (when (seq xs)
   (apply conj clojure.lang.PersistentQueue/EMPTY xs)))
 
(defn level-order [root f]
  (loop [q (queue root)]
    (when-not (empty? q)
      (if-let [node (first q)]
        (do
          (f (:val node))
          (recur (conj (pop q) (:left node) (:right node))))
        (recur (pop q))))))
 
(defn vec-to-tree [t]
  (if (vector? t)
    (let [[val left right] t]
      {:val val
       :left (vec-to-tree left)
       :right (vec-to-tree right)})
    t))
 
(let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]])
      fs   '[preorder inorder postorder level-order]
      pr-node #(print (format "%2d" %))]
  (doseq [f fs]
    (print (format "%-12s" (str f ":")))
    ((resolve f) tree pr-node)
    (println)))