Problem

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 109 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?

Examples

Example 1:

1
2
3
4
5
![](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1600-1699/1628.Design%20an%20Expression%20Tree%20With%20Evaluate%20Function/images/untitled-
diagram.png)
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:

1
2
3
4
5
![](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1600-1699/1628.Design%20an%20Expression%20Tree%20With%20Evaluate%20Function/images/untitled-
diagram2.png)
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 < 100
  • s.length is odd.
  • s consists of numbers and the characters '+', '-', '*', and '/'.
  • If s[i] is a number, its integer representation is no more than 105.
  • It is guaranteed that s is a valid expression.
  • The absolute value of the result and intermediate values will not exceed 109.
  • It is guaranteed that no expression will include division by zero.

Solution

Method 1 – Stack-Based Tree Construction and Polymorphic Evaluation

Intuition

We can build the expression tree from the postfix tokens using a stack. For each token, if it’s a number, create a leaf node and push it onto the stack. If it’s an operator, pop two nodes from the stack, create an operator node with them as children, and push it back. For evaluation, use polymorphism: each node type implements its own evaluate method. This design is modular and easily extensible for new operators.

Approach

  1. Define a base Node class with an evaluate method.
  2. Implement NumNode for numbers and OpNode for operators, both inheriting from Node.
  3. For each token in the postfix list:
    • If it’s a number, create a NumNode and push to the stack.
    • If it’s an operator, pop two nodes, create an OpNode, and push to the stack.
  4. The last node on the stack is the root of the expression tree.
  5. To evaluate, call evaluate() on the root node.

Code

 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
class Node:
    def evaluate(self) -> int:
        raise NotImplementedError
class NumNode(Node):
    def __init__(self, val: int):
        self.val = val
    def evaluate(self) -> int:
        return self.val
class OpNode(Node):
    def __init__(self, op: str, left: Node, right: Node):
        self.op = op
        self.left = left
        self.right = right
    def evaluate(self) -> int:
        l, r = self.left.evaluate(), self.right.evaluate()
        if self.op == '+': return l + r
        if self.op == '-': return l - r
        if self.op == '*': return l * r
        if self.op == '/': return int(l / r)
        raise ValueError('Unknown operator')
class TreeBuilder:
    def buildTree(self, postfix: list[str]) -> Node:
        stack = []
        for token in postfix:
            if token in '+-*/':
                r = stack.pop()
                l = stack.pop()
                stack.append(OpNode(token, l, r))
            else:
                stack.append(NumNode(int(token)))
        return stack[-1]
 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
import java.util.*;
abstract class Node {
    public abstract int evaluate();
}
class NumNode extends Node {
    int val;
    public NumNode(int v) { val = v; }
    public int evaluate() { return val; }
}
class OpNode extends Node {
    String op;
    Node left, right;
    public OpNode(String o, Node l, Node r) { op = o; left = l; right = r; }
    public int evaluate() {
        int lval = left.evaluate(), rval = right.evaluate();
        switch (op) {
            case "+": return lval + rval;
            case "-": return lval - rval;
            case "*": return lval * rval;
            case "/": return lval / rval;
        }
        throw new IllegalArgumentException();
    }
}
class TreeBuilder {
    public Node buildTree(String[] postfix) {
        Stack<Node> stack = new Stack<>();
        for (String token : postfix) {
            if ("+-*/".contains(token)) {
                Node r = stack.pop(), l = stack.pop();
                stack.push(new OpNode(token, l, r));
            } else {
                stack.push(new NumNode(Integer.parseInt(token)));
            }
        }
        return stack.peek();
    }
}