/* * Each node in the tree holds a String that is either a binary operator * (restricted to "+", "-", "*", "/") or can be treated as an integer value. */ public class ExpressionTreeDemo { public static void main(String[] args) { /* build and evaluate the binary tree for ((4+3)*(10-5))/2 */ /* build it from the bottom up */ 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"); /* build the actual tree structure */ BinaryTree plus = new BinaryTree("+", four, three); BinaryTree minus = new BinaryTree("-", ten, five); BinaryTree times = new BinaryTree("*", plus, minus); BinaryTree divide = new BinaryTree("/", times, two); /* what's the answer */ System.out.println(evaluate(divide)); } public static int evaluate(BinaryTree tree) { if (tree.isLeaf()) { return Integer.parseInt(tree.value()); } else { int left = evaluate(tree.left()); int right = evaluate(tree.right()); String op = tree.value(); if (op.equals("+")) { return left + right; } else if (op.equals("-")) { return left - right; } else if (op.equals("*")) { return left * right; } else if (op.equals("/")) { return left / right; } else { throw new IllegalStateException("bad op: " + op); } } } }