Data Structures, Algorithms, & Applications in Java
Chapter 12, Exercise 21
We create a class with the static data members
a and
last. The public method
inOrder simply sets these
data members and invokes the recursive method
theInOrder, which
does the actual traversal.
The code is given below. The test program and output
are in the files
ArrayBinaryTreeWithInorder.*.
public class ArrayBinaryTreeWithInorder
{
// data members
static Object [] a; // array that contains the tree
static int last; // position of last element in array a
/** visit method that prints the element in a[i] */
public static void visit(int i)
{System.out.print(a[i] + " ");}
/** inorder traversal */
public static void inOrder(Object [] theArray, int theLast)
{
// set static data members
a = theArray;
last = theLast;
// start the recursive traversal method at the root
theInOrder(1);
}
/** actual method to do the inorder traversal */
static void theInOrder(int i)
{// traverse subtree rooted at a[i]
if (i <= last && a[i] != null)
{// root exists
theInOrder(2 * i); // do left subtree
visit(i); // visit tree root
theInOrder(2 * i + 1); // do right subtree
}
}
}