|
| 1 | +/** |
| 2 | + * This is the interface for the expression tree Node. |
| 3 | + * You should not remove it, and you can define some classes to implement it. |
| 4 | + */ |
| 5 | + |
| 6 | +abstract class Node { |
| 7 | + public abstract int evaluate(); |
| 8 | + // define your fields here |
| 9 | +}; |
| 10 | + |
| 11 | +class NumericNode extends Node { |
| 12 | + |
| 13 | + private int val; |
| 14 | + |
| 15 | + public NumericNode(int val) { |
| 16 | + this.val = val; |
| 17 | + } |
| 18 | + |
| 19 | + public int evaluate() { |
| 20 | + return this.val; |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +class OperatorNode extends Node { |
| 25 | + private char operator; |
| 26 | + private Node leftNode; |
| 27 | + private Node rightNode; |
| 28 | + |
| 29 | + public OperatorNode(char operator, Node leftNode, Node rightNode) { |
| 30 | + this.operator = operator; |
| 31 | + this.leftNode = leftNode; |
| 32 | + this.rightNode = rightNode; |
| 33 | + } |
| 34 | + |
| 35 | + public int evaluate() { |
| 36 | + int leftValue = this.leftNode == null ? 0 : this.leftNode.evaluate(); |
| 37 | + int rightValue = this.rightNode == null ? 0 : this.rightNode.evaluate(); |
| 38 | + if (this.operator == '+') { |
| 39 | + return leftValue + rightValue; |
| 40 | + } else if (this.operator == '-') { |
| 41 | + return leftValue - rightValue; |
| 42 | + } else if (this.operator == '*') { |
| 43 | + return leftValue * rightValue; |
| 44 | + } else { |
| 45 | + return leftValue / rightValue; |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | + |
| 51 | +/** |
| 52 | + * This is the TreeBuilder class. |
| 53 | + * You can treat it as the driver code that takes the postinfix input |
| 54 | + * and returns the expression tree represnting it as a Node. |
| 55 | + */ |
| 56 | + |
| 57 | +class TreeBuilder { |
| 58 | + Node buildTree(String[] postfix) { |
| 59 | + Stack<Node> stack = new Stack<>(); |
| 60 | + for(String token: postfix){ |
| 61 | + if (token.equals("*") || token.equals("+") || token.equals("-") || token.equals("/")) { |
| 62 | + Node o2 = stack.pop(); |
| 63 | + Node o1 = stack.pop(); |
| 64 | + stack.push(new OperatorNode(token.charAt(0), o1, o2)); |
| 65 | + } else{ |
| 66 | + stack.push(new NumericNode(Integer.parseInt(token))); |
| 67 | + } |
| 68 | + } |
| 69 | + return stack.pop(); |
| 70 | + } |
| 71 | +}; |
| 72 | + |
| 73 | + |
| 74 | +/** |
| 75 | + * Your TreeBuilder object will be instantiated and called as such: |
| 76 | + * TreeBuilder obj = new TreeBuilder(); |
| 77 | + * Node expTree = obj.buildTree(postfix); |
| 78 | + * int ans = expTree.evaluate(); |
| 79 | + */ |
0 commit comments