next up previous index
Next: elementsInOrder for the NodeTree Up: Binary Search Trees Previous: Enumerations   Index


elementsLevelOrder for the NodeTree class

Implementation of these enumerations for the NodeTree class is harder work. We shall deal with the level order traversal first, because the code is shorter. It is shown in Figure 8.4.

Figure 8.4: Implementation of level order tree traversal.
public Enumeration elementsLevelOrder() {
    return new Enumeration() {
        private Queue q = new QueueArray();
        {
            q.enqueue(NodeTree.this);
        }
        public boolean hasMoreElements() {
            return !q.isEmpty();
        }
        public Object nextElement() {
            NodeTree root = (NodeTree) q.dequeue();
            if (!root.left.isEmpty()) {
                q.enqueue(root.left);
            }
            if (!root.right.isEmpty()) {
                q.enqueue(root.right);
            }
            return root.data;
        }
    };
}

As for our LinkedList.elements method, we code elementsLevelOrder to return a new instance of a locally defined anonymous class. The class implements the Enumeration interface, so it has to implement the hasMoreElements and nextElement methods. It does this by using its own private queue. For definiteness we have used the array implementation of a queue. The queue q is initialised by enqueuing the tree we are about to enumerate. Note the need for the qualified NodeTree.this. If we used this on its own, it would refer to this Enumeration.

The core of the algorithm is in the nextElement method. This returns the data from the node at the head of the queue, and places the left and right subtrees in the queue for processing. When the left subtree comes to be processed, its own children will be placed in the queue, but behind the right subtree of the original parent tree. In this way the nodes are enumerated according to their depth in the tree, from left to right.


next up previous index
Next: elementsInOrder for the NodeTree Up: Binary Search Trees Previous: Enumerations   Index
Peter Williams 2005-06-07