/************************************************************************* * Compilation: javac DrawableParseTree.java * Execution: java DrawableParseTree * Dependencies: StdIn.java StdDraw.java * * Evaluates a prefix expression by explicitly building the parse * tree and doing a preorder traversal. Also draws the binary tree. * * * % java DrawableParseTree * * + + 4 5 * 6 7 8 // corresponds to (((4+5)+(6*7))*8) * // use on Windows for EOF * 408 // the answer * * * Limitations * ----------- * Assumes the depth is at most 5; otherwise will go outside boundary. * * *************************************************************************/ import java.awt.Color; public class DrawableParseTree { private static int WIDTH = 800, HEIGHT = 600; private String s; private DrawableParseTree left, right; // creat the parse tree from standard input public DrawableParseTree() { s = StdIn.readString(); if (s.equals("+") || s.equals("*")) { left = new DrawableParseTree(); right = new DrawableParseTree(); } } // evalute the parse tree public int eval() { if (s.equals("+")) return left.eval() + right.eval(); else if (s.equals("*")) return left.eval() * right.eval(); else return Integer.parseInt(s); } // evalute the parse tree public void draw() { draw(WIDTH / 2, HEIGHT - 50, WIDTH / 4); } private void draw(double x, double y, double width) { final double height = 100.0; StdDraw.setColor(Color.BLACK); StdDraw.moveTo(x, y); StdDraw.lineTo(x - width, y - height); StdDraw.moveTo(x, y); StdDraw.lineTo(x + width, y - height); StdDraw.moveTo(x, y); StdDraw.spot(30); StdDraw.setColor(Color.WHITE); StdDraw.write(s); if (s.equals("+") || s.equals("*")) { left.draw (x - width, y - height, width / 2.0); right.draw(x + width, y - height, width / 2.0); } } public static void main(String[] args) { DrawableParseTree tree = new DrawableParseTree(); System.out.println(tree.eval()); StdDraw.create(WIDTH, HEIGHT); StdDraw.setScale(0, 0, WIDTH, HEIGHT); StdDraw.clear(Color.WHITE); tree.draw(); StdDraw.show(); } }