// package Trees; /** * ExpressionTree.java * * * Created: Tue Apr 1 14:23:47 2003 * * @author <a href="mailto:shapiro@cse.buffalo.edu">Stuart C. Shapiro</a> */ public class ExpressionTree extends BinaryTree { /** * Creates a new empty <code>ExpressionTree</code> instance. * */ public ExpressionTree (){ super(); } /** * Creates a new <code>ExpressionTree</code> instance. * * @param value contents of this node of this tree. * @param lt the left sub-<code>BinaryTree</code> of this tree. * @param rt the right sub-<code>BinaryTree</code> of this tree. */ public ExpressionTree (Object value, ExpressionTree lt, ExpressionTree rt) { super(value, lt, rt); } public static ExpressionTree operand(Object v) { ExpressionTree opnd = new ExpressionTree(); opnd.setContents(v); return opnd; } public String preorderToString() { if (isEmpty()) return ""; if (isLeaf()) return "" + getContents() + " "; return "" + getContents() + " " + ((ExpressionTree)getLeft()).preorderToString() + ((ExpressionTree)getRight()).preorderToString(); } public String inorderToString() { if (isEmpty()) return ""; if (isLeaf()) return "" + getContents(); return "(" + ((ExpressionTree)getLeft()).inorderToString() + " " + getContents() + " " + ((ExpressionTree)getRight()).inorderToString() + ")"; } public String postorderToString() { if (isEmpty()) return ""; if (isLeaf()) return "" + getContents() + " "; return ((ExpressionTree)getLeft()).postorderToString() + ((ExpressionTree)getRight()).postorderToString() + " " + getContents() + " "; } public static void main (String[] args) { // ((5 * (10 - 4)) / (18 / (2 * 3))) ExpressionTree expr = new ExpressionTree("/", new ExpressionTree("*", operand("5"), new ExpressionTree("-", operand("10"), operand("4"))), new ExpressionTree("/", operand("18"), new ExpressionTree("*", operand("2"), operand("3")))); System.out.println("As binary tree: " + expr); System.out.println("Inorder: " + expr.inorderToString()); System.out.println("Preorder: " + expr.preorderToString()); System.out.println("Postorder: " + expr.postorderToString()); } // end of main () }// ExpressionTree