More Tree Traversals


Generic IreOrder Tree Traversal:

// recursive version
    private void preorder_traversal(TreeNode t)
    {
        if (null != t)
        {
            preorder_traversal(t.left);
            System.out.print(t.element + " ");
            preorder_traversal(t.right);
        }
    } // end preorder_traversal


//non-recursive version with explicit use of stacks
private void preorder(TreeNode t)
{
   Stack s = new Stack();
   TreeNode n;

    s.push(t);

    while (!s.isEmpty())
{
        n = (TreeNode) s.pop();
        if (null != n) {
           System.outlprint(n.element);
           s.push(n.right);
           s.push(n.left);
        } // end if
  } // end while
} // end preorder


// level order traversal (breadth first search)
private void levelOrder (TreeNode t)
{
    Queue q = new Queue();
    TreeNode n;

    q.enqueue(t);

    while (!q.isEmpty())
    {
        n = (TreeNode) q.dequeue();
        if (null != n)
       {
            System.out.print(n.info);
              q.enqueue(n.left);
              q.enqueue(n.right);
        } // end if
    } // end while
} end levelOrder