1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
abstract class Node { public abstract int evaluate();
public int num; public String operand; public Node left; public Node right; };
class TreeNode extends Node {
public int evaluate() { if (this.operand == null) { return this.num; } int leftTreeVal = this.left.evaluate(); int rightTreeVal = this.right.evaluate(); int ans = compute(leftTreeVal, rightTreeVal, this.operand); return ans; }
public TreeNode(int num) { this.num = num; }
public TreeNode(String operand) { this.operand = operand; }
public int compute(int i, int j, String operand) { int ans = 0; switch (operand) { case "+": ans = i + j; break; case "-": ans = i - j; break; case "*": ans = i * j; break; case "/": ans = i / j; break; } return ans; } }
class TreeBuilder { Node buildTree(String[] postfix) { Deque<Node> stack = new ArrayDeque<>(); for (String s : postfix) { if (!isOperand(s)) { stack.push(new TreeNode(Integer.parseInt(s))); } else { Node rightNode = stack.pop(); Node leftNode = stack.pop(); Node currNode = new TreeNode(s); currNode.left = leftNode; currNode.right = rightNode; stack.push(currNode); } } return stack.pop(); }
public boolean isOperand(String s) { return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/"); } };
|