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.


 
#lang racket
 
(define the-tree ; Node: (list <data> <left> <right>)
  '(1 (2 (4 (7 #f #f) #f) (5 #f #f)) (3 (6 (8 #f #f) (9 #f #f)) #f)))
 
(define (preorder tree visit)
  (let loop ([t tree])
    (when t (visit (car t)) (loop (cadr t)) (loop (caddr t)))))
(define (inorder tree visit)
  (let loop ([t tree])
    (when t (loop (cadr t)) (visit (car t)) (loop (caddr t)))))
(define (postorder tree visit)
  (let loop ([t tree])
    (when t (loop (cadr t)) (loop (caddr t)) (visit (car t)))))
(define (levelorder tree visit)
  (let loop ([trees (list tree)])
    (unless (null? trees)
      ((compose1 loop (curry filter values) append*)
       (for/list ([t trees] #:when t) (visit (car t)) (cdr t))))))
 
(define (run order)
  (printf "~a:" (object-name order))
  (order the-tree (λ(x) (printf " ~s" x)))
  (newline))
(for-each run (list preorder inorder postorder levelorder))
 