From charlesreid1

Revision as of 18:41, 18 June 2017 by Admin (talk | contribs)

First, we have a high level interface called Tree, which has a method called positions() returning an iterable container with all positions in the tree:

public interface Tree<E> extends Iterable<E> {
	public Iterable<Position<E>> positions();
}

Once the interface defines that, any concrete classes implementing that interface must implement that method. Here is a concrete class that implements the Tree interface, and implement s a position() method to assemble all of the positions in the tree:

public class LinkedBinTree<E> implements Tree<E> {

	/** Define a method that returns an iterable Position pointer that 
	 * iterates through the tree in the specified order. */
	public Iterable<Position<E>> positions() { return preorder(); }


	/** Pre-order tree traversal. 
	 *
	 * This returns an iterable.
	 * Pre-order means the visit action is performed on the node
	 * before any of its children are visited. 
	 * This is a recursive method. */ 
	public Iterable<Position<E>> preorder() {
		List<Position<E>> snapshot = new LinkedList<Position<E>>();
		preorderSubtree(root(), snapshot);
		return snapshot;
	}

	/** Preorder traversal, with a specific subtree. */
	public Iterable<Position<E>> preorder(Position<E> p) {
		List<Position<E>> snapshot = new LinkedList<Position<E>>();
		preorderSubtree(p, snapshot);
		return snapshot;
	}

	/** Utility method for pre-order tree traversal. */
	private void preorderSubtree(Position<E> p, List<Position<E>> snapshot) { 
		// Base case is, no children, no loop.
		// Recursive case is, this will be called on child nodes.

		// 1. Perform visit action for Position p
		snapshot.add(p);

		// 2. Recurse through children
		for(Position<E> c : children(p)) {
			preorderSubtree(c,snapshot);
		}
	}