// file ExpressionTree.java // Expression tree. The internal nodes are labelled with the // characters '+', -', '*', and '/' and correspond to these operations. // The leaves have label 'C' (for constant). The leaves have their // value in an int field value. public class ExpressionTree extends BinaryTree { private int value; // Constructor for leaf node public ExpressionTree (int v) { setLabel(new Character('C')); value = v; } // // Constructor for internal node public ExpressionTree(Character c, ExpressionTree l, ExpressionTree r) { setLabel(c); setLeft(l); setRight(r); } // Get the left or right hand subtree, annd cast it as an ExpressionTree public ExpressionTree expLeft() { return (ExpressionTree) getLeft(); } public ExpressionTree expRight() { return (ExpressionTree) getRight(); } // Evaluate a node public int evaluate() { switch (getLabel()) { case 'C': return value; case '+': return expLeft().evaluate() + expRight().evaluate(); case '-': return expLeft().evaluate() - expRight().evaluate(); case '*': return expLeft().evaluate() * expRight().evaluate(); case '/': return expLeft().evaluate() / expRight().evaluate(); default: return 0; // should never reach this case } } public void displayNode(int indent) { for (int i=0; i < indent; i++) System.out.print(" "); if (getLabel() == 'C') System.out.println(value); else System.out.println(getLabel()); } public String parenthesizedExp() { if (getLabel()=='C') return new Integer(value).toString(); else return "(" + expLeft().parenthesizedExp() + " " + getLabel() + " " + expRight().parenthesizedExp() + ")"; } }