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.


def preorder:
  if length == 0 then empty
  else .[0], (.[1]|preorder), (.[2]|preorder)
  end;
 
def inorder:
  if length == 0 then empty
  else (.[1]|inorder), .[0] , (.[2]|inorder)
  end;
 
def postorder:
  if length == 0 then empty
  else (.[1] | postorder), (.[2]|postorder), .[0]
  end;
 
# Helper functions for levelorder:
  # Produce a stream of the first elements
  def heads: map( .[0] | select(. != null)) | .[];
 
# Produce a stream of the left/right branches:
  def tails:
    if length == 0 then empty
    else [map ( .[1], .[2] ) | .[] | select( . != null)]
    end;
 
def levelorder: [.] | recurse( tails ) | heads;
 