// Takes an operator, pops appropriate number of operands from // operand stack, builds them into a new subtree and pushes the // subtree back to the operand stack. private void buildNewSubtree(InnerNode op) { // take op2, build new subtree and push to operand stack Object topOperand = operandStack.Pop(); // can be LeafNode or MathTree (subtree) if (topOperand is LeafNode) { LeafNode leafNode1 = (LeafNode)topOperand; if (op.numArgs() == 2) // binary operator { Object nextOperand = operandStack.Pop(); if (nextOperand is LeafNode) { LeafNode leafNode2 = (LeafNode)nextOperand; MathTree newSubtree = this.joinTrees(op, leafNode1, leafNode2); operandStack.Push(newSubtree); } else { MathTree subtree2 = (MathTree)nextOperand; MathTree newSubtree = this.joinTrees(op, leafNode1, subtree2); operandStack.Push(newSubtree); } } else // unary operator { MathTree newSubtree = this.joinTrees(op, leafNode1); operandStack.Push(newSubtree); } } else { MathTree subtree1 = (MathTree)topOperand; if (op.numArgs() == 2) // binary operator { Object nextOperand = operandStack.Pop(); if (nextOperand is LeafNode) { LeafNode leafNode2 = (LeafNode)nextOperand; MathTree newSubtree = this.joinTrees(op, subtree1, leafNode2); operandStack.Push(newSubtree); } else { MathTree subtree2 = (MathTree)nextOperand; MathTree newSubtree = this.joinTrees(op, subtree1, subtree2); operandStack.Push(newSubtree); } } else // unary operator { MathTree newSubtree = this.joinTrees(op, subtree1); operandStack.Push(newSubtree); } } }