Data Structures, Algorithms, & Applications in Java
Chapter 12, Exercise 23
Since the elements are stored in the array by levels, a level
order traversal may be done by examining the array from left
to right.
The code is given below. The test program and output
are in the files
ArayBinaryTreeWithLevelOrder.*.
public class ArrayBinaryTreeWithLevelOrder
{
static Object [] a; // array that contains the tree
/** visit method that prints the element in a[i] */
public static void visit(int i)
{System.out.print(a[i] + " ");}
/** level order traversal */
public static void levelOrder(Object [] theArray, int last)
{
a = theArray;
for (int i = 1; i <= last; i++)
if (a[i] != null)
visit(i);
}
}