/** * A demo of evaluating an expression stored as an expression tree. */ public class ExpressionTreeDemo { /** * Build and evaluate a binary tree for (((4+3)*(10-5))/2). */ public static void main(String[] args) { BinaryTree four = new BinaryTree("4"); BinaryTree three = new BinaryTree("3"); BinaryTree ten = new BinaryTree("10"); BinaryTree five = new BinaryTree("5"); BinaryTree two = new BinaryTree("2"); BinaryTree plus = new BinaryTree("+", four, three); BinaryTree minus = new BinaryTree("-", ten, five); BinaryTree times = new BinaryTree("*", plus, minus); BinaryTree divide = new BinaryTree("/", times, two); System.out.println(evaluate(divide)); } /** * Evaluate an expression stored in a binary expression tree */ public static double evaluate(BinaryTree tree) { if (tree.isLeaf()) { return Double.parseDouble(tree.value()); } else { double leftVal = evaluate(tree.left()); double rightVal = evaluate(tree.right()); String op = tree.value(); if (op.equals("+")) { return leftVal + rightVal; } else if (op.equals("-")) { return leftVal - rightVal; } else if (op.equals("*")) { return leftVal * rightVal; } else if (op.equals("/")) { return leftVal / rightVal; } else { throw new IllegalArgumentException("unrecognized operator " + op); } } } }