// Tree.java // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes. // It provides iterators that loop over children, that loop up to the root, // and that traverse the tree in prefix and postfix order. // class Tree { private T label; private Tree parent; private Tree nextSibling; // next node on the list of parents's // children private Tree firstChild; // first in the linked list of children // Getters and setters public T getLabel() { return label; } public void setLabel(T v) { label = v; } public Tree getParent() { return parent;} public Tree getNextSibling() { return nextSibling;} public Tree getFirstChild() { return firstChild;} public Tree getSelf() { return this; } // Add C to the front of the children of this public void addChild(Tree c) { c.parent = this; if (firstChild == null) firstChild = c; else { c.nextSibling = firstChild; firstChild = c; } } // Check if the node is a leaf public boolean Leaf() { return firstChild==null; } public Tree nextPreorder() { if (getFirstChild() != null) return getFirstChild(); else { Tree a=this; while (a.getNextSibling() == null && a.getParent() != null) a=a.getParent(); return a.getNextSibling(); } } }