Design an Expression Tree With Evaluate Function Problem
Description
LeetCode Problem 1628.
Given the postfix tokens of an arithmetic expression, build and return the binary expression tree that represents this expression.
Postfix notation is a notation for writing arithmetic expressions in which the operands (numbers) appear before their operators. For example, the postfix tokens of the expression 4*(5-(7+2)) are represented in the array postfix = ["4","5","7","2","+","-","*"].
The class Node is an interface you should use to implement the binary expression tree. The returned tree will be tested using the evaluate function, which is supposed to evaluate the tree's value. You should not remove the Node class; however, you can modify it as you wish, and you can define other classes to implement it if needed.
A binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (numbers), and internal nodes (nodes with two children) correspond to the operators '+' (addition), '-' (subtraction), '*' (multiplication), and '/' (division).
It's guaranteed that no subtree will yield a value that exceeds 10^9 in absolute value, and all the operations are valid (i.e., no division by zero).
Follow up: Could you design the expression tree such that it is more modular? For example, is your design able to support additional operators without making changes to your existing evaluate implementation?
Example 1:

Input: s = ["3","4","+","2","*","7","/"]
Output: 2
Explanation: this expression evaluates to the above binary tree with expression ((3+4)*2)/7) = 14/7 = 2.
Example 2:

Input: s = ["4","5","2","7","+","-","*"]
Output: -16
Explanation: this expression evaluates to the above binary tree with expression 4*(5-(2+7)) = 4*(-4) = -16.
Constraints:
1 <= s.length < 100s.lengthis odd.sconsists of numbers and the characters'+','-','*', and'/'.- If
s[i]is a number, its integer representation is no more than10^5. - It is guaranteed that
sis a valid expression. - The absolute value of the result and intermediate values will not exceed
10^9. - It is guaranteed that no expression will include division by zero.
Solution
Approach: Build With a Stack, Evaluate Recursively
In postfix notation an operator always comes right after its two operands, so a stack rebuilds the tree in one pass:
- A number becomes a leaf node and is pushed.
- An operator pops two nodes and becomes their parent. The node popped first is the right operand, because it was pushed last; mixing them up breaks
-and/.
At the end the stack holds exactly one node, the root.
For the evaluation, use two kinds of nodes that implement the Node interface:
- a number node, whose
evaluatereturns its value; - an operator node, whose
evaluateevaluates both children and combines them.
For the follow-up, the operator node does not switch over the operator symbols. It looks the symbol up in a table that maps each operator to a function, so a new operator only needs a new table entry, and evaluate itself never changes.
Division is integer division that truncates toward zero, as in Java, C++ and Go; the Python and JavaScript versions spell this out, because Python's // rounds down and JavaScript's / gives a fraction.
Complexity: O(n) time to build the tree and to evaluate it, and O(n) space for the nodes and the stack.
from abc import ABC, abstractmethod
"""
This is the interface for the expression tree Node.
You should not remove it, and you can define some classes to implement it.
"""
class Node(ABC):
@abstractmethod
# define your fields here
def evaluate(self) -> int:
pass
class NumberNode(Node):
def __init__(self, value: int):
self.value = value
def evaluate(self) -> int:
return self.value
class OperatorNode(Node):
# Each operator is a function, so a new one only needs a new entry here.
OPERATIONS = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
# Integer division that truncates toward zero.
"/": lambda x, y: abs(x) // abs(y) * (1 if (x >= 0) == (y > 0) else -1),
}
def __init__(self, op: str, left: Node, right: Node):
self.op, self.left, self.right = op, left, right
def evaluate(self) -> int:
return OperatorNode.OPERATIONS[self.op](self.left.evaluate(), self.right.evaluate())
"""
This is the TreeBuilder class.
You can treat it as the driver code that takes the postinfix input
and returns the expression tree representing it as a Node.
"""
class TreeBuilder(object):
def buildTree(self, postfix: List[str]) -> 'Node':
stack = []
for token in postfix:
if token in OperatorNode.OPERATIONS:
right = stack.pop() # the right operand was pushed last
left = stack.pop()
stack.append(OperatorNode(token, left, right))
else:
stack.append(NumberNode(int(token)))
return stack[-1]