// 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 { // implements Iterable { 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;} // 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; } // `Convert the tree into a string. The structure is indicated by // square brackets. Uses a preorder listing. public String toString() { String S = "[ " + label.toString(); Tree N = firstChild; while (N != null) { S = S + " " + N.toString(); N = N.nextSibling; } return S+" ]"; } public void displayPreorder() { displayPreorder1(0); } public void displayPreorder1(int Indent) { for (int I = 0; I < Indent; I++) System.out.print(" "); System.out.println(label.toString()); Tree N = firstChild; while (N != null) { N.displayPreorder1(Indent+3); N = N.nextSibling; } } public void displayPostorder() { displayPostorder1(0); } public void displayPostorder1(int Indent) { Tree N = firstChild; while (N != null) { N.displayPostorder1(Indent+3); N = N.nextSibling; } for (int I = 0; I < Indent; I++) System.out.print(" "); System.out.println(label.toString()); } }