class Tree { String tag; // What kind of node we are. String spelling; // If we're an Id, our spelling. int value; // If we're a number, our value. Tree first; // First child. Other children linked as siblings to this. Tree next; // Our sibling. Forms linked list. /* ------------------------------------------------------------------------- */ // Create a leaf node with a spelling. Tree(String s) { tag = "Id"; spelling = s; } // Create a leaf node with a value. Tree(int v) { tag = "Num"; value = v; } // Create a node with one child. Tree(String t, Tree c1) { tag = t; first = c1; } // Create a node with two children. Tree(String t, Tree c1, Tree c2) { tag = t; first = c1; c1.next = c2; } /* ------------------------------------------------------------------------- */ // Add more children to a node. void appendChild(Tree newChild) { if (first == null) first = newChild; // It's our first child. else { Tree last = first; // Not really the last child, but will be. while (last.next != null) last = last.next; // Find last child. last.next = newChild; // Now it's the last, so we append to it. } } /* ------------------------------------------------------------------------- */ // Preorder traversal of syntax tree, returning string with indent formatting. String toStringAll(int depth, String result) { for (int i = 0; i < depth; i++) result += "| "; // Indenting. result += tag + " "; if (tag == "Id") result += spelling; else if (tag == "Num") result += new Integer(value).toString(); result += "\n"; if (first != null) result = first.toStringAll(depth+1, result); // One level deeper. if (next != null) result = next .toStringAll(depth , result); // Same level. return result; } /* ------------------------------------------------------------------------- */ // The wrapper the outside world sees. Sets initial indent level to 0. public String toString() { return toStringAll(0, ""); } } /* ========================================================================= */ class P3 { static Tree prog1() { Tree sum = new Tree("Sum", new Tree(5), new Tree(3)); // 5 + 3 Tree s1 = new Tree("AssignStmt", new Tree("a"), sum); // a = 5 + 3 Tree prod = new Tree("Product", new Tree(7), new Tree(1)); // 7 * 1 Tree s2 = new Tree("AssignStmt", new Tree("b"), prod); // b = 7 * 1 Tree sum2 = new Tree("Sum", new Tree("a"), new Tree("b")); // a + b Tree s3 = new Tree("AssignStmt", new Tree("c"), sum2); // c = a + b Tree cmds = new Tree("StatementList", s1); cmds.appendChild(s2); cmds.appendChild(s3); return cmds; } public static void main(String[] args) { System.out.println(prog1()); } }