1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes. class Tree<T> { private T label; private Tree<T> parent; private Tree<T> nextSibling; // next node on the list of parents's // children private Tree<T> 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<T> getParent() { return parent;} public Tree<T> getNextSibling() { return nextSibling;} public Tree<T> getFirstChild() { return firstChild;} // Add C to the front of the children of this public void addChild(Tree<T> 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<T> 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<T> N = firstChild; while (N != null ) { N.displayPreorder1(Indent+ 3 ); N = N.nextSibling; } } public void displayPostorder() { displayPostorder1( 0 ); } public void displayPostorder1( int Indent) { Tree<T> 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()); } } |