public class TreeNode implements Position { private Object element; // the data object stored at this position private TreeNode leftChild; // leftmost child; null if no children private TreeNode rightSibling; // next child to the right; null if last private TreeNode parent; // parent; null if the root // *** BASIC ACCESSORS FOR THE FIELDS public Object element() { // required to implement the Position interface return element; } public TreeNode leftChild() { return leftChild; } public TreeNode rightSibling() { return rightSibling; } public TreeNode parent() { return parent; } // *** CONVENIENCE METHODS public boolean isInternal() { return (leftChild != null); } public boolean isRoot() { return (parent == null); } // *** ITERATORS /* Iterates over all children from left to right. */ public TreeChildrenIterator children() { return new TreeChildrenIterator(this); } /* Iterates over all proper ancestors from bottom to top. */ public TreeAncestorsIterator ancestors() { return new TreeAncestorsIterator(this); } /* Iterates over this node and all descendants, in prefix order. */ public TreePreorderIterator descendants_preorder() { return new TreePreorderIterator(this); } public TreePreorderIterator descendants_proper_preorder() { TreePreorderIterator iter = descendants_preorder(); iter.next(); // get and throw away first return value, namely "this" return iter; // now the iterator will only return proper descendants } // *** EXAMPLE // Typical use of an iterator is shown by this code, which prints out // a node and its descendants in prefix order: // // Iterator iter = p.descendants_preorder(); // while (i.hasNext()) // ((String)i.next()).print(); }