Talentd
FleetCode
Make and follow sheets.Sign in

Design an Expression Tree With Evaluate Function solution and explanation

MediumArrayBinary TreeDesignMath5 min read82.4% acceptanceUpdated 23 Mar 2026Premium elsewhere, free here
1628. Design an Expression Tree With Evaluate Function (Leetcode Medium)Programming Live with Larry · 12:06 · 591 viewsWatch on YouTube
1 more video on this problem
  1. 1628. Design an Expression Tree With Evaluate Function (Leetcode Medium)Programming Live with Larry · 12:06 · 591 views
  2. Arithmetic Binary Tree (Leetcode 1628) | LeetCode TutorialJomaClass · 6:27 · 130 views

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

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 < 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.

Approach overview

Problem Overview: You receive a postfix (Reverse Polish Notation) expression and must build an expression tree that can evaluate itself. Each node represents either an operand (number) or an operator (+, -, *, /). The goal is to design the tree structure and implement an evaluate() method that computes the expression result.

Approach 1: Stack-Based Expression Tree Construction (O(n) time, O(n) space)

The postfix expression naturally fits a stack-based algorithm. Iterate through each token in the array. If the token is a number, create a node and push it onto the stack. If the token is an operator, pop two nodes from the stack (right operand first, then left), create a new operator node, and attach the popped nodes as children. Push the new subtree root back onto the stack. After processing all tokens, the stack contains the root of the complete binary tree. Implement evaluate() recursively: leaf nodes return their integer value, while operator nodes evaluate left and right subtrees and apply the stored operator.

This approach works because postfix notation guarantees that operands appear before the operator that uses them. The stack always maintains partially built subtrees until an operator combines them.

Approach 2: Recursive Evaluation on Constructed Tree (O(n) time, O(h) space)

Once the expression tree is built, evaluation becomes a standard tree traversal problem. Each operator node depends on the results of its children, which makes a postorder traversal ideal. Recursively call evaluate() on the left and right children, then apply the operator stored in the current node. Operands immediately return their numeric value.

This recursion uses the call stack proportional to the tree height h. In the worst case (skewed tree) space becomes O(n), but typical expression trees are balanced, keeping recursion depth smaller.

The combination of stack-based construction and recursive evaluation cleanly separates responsibilities: building the structure first, then computing results using tree semantics. This design pattern appears frequently in compiler parsing and interpreter implementations.

Recommended for interviews: The stack-based construction combined with recursive evaluation is the expected solution. It demonstrates understanding of postfix parsing, tree design, and recursion. A brute-force evaluation of the postfix expression alone would miss the key requirement of designing the expression tree class.

Solution

import abc
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 MyNode(Node):
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

    def evaluate(self) -> int:
        x = self.val
        if x.isdigit():
            return int(x)

        left, right = self.left.evaluate(), self.right.evaluate()
        if x == '+':
            return left + right
        if x == '-':
            return left - right
        if x == '*':
            return left * right
        if x == '/':
            return left // right


"""
This is the TreeBuilder class.
You can treat it as the driver code that takes the postinfix input
and returns the expression tree represnting it as a Node.
"""


class TreeBuilder(object):
    def buildTree(self, postfix: List[str]) -> 'Node':
        stk = []
        for s in postfix:
            node = MyNode(s)
            if not s.isdigit():
                node.right = stk.pop()
                node.left = stk.pop()
            stk.append(node)
        return stk[-1]


"""
Your TreeBuilder object will be instantiated and called as such:
obj = TreeBuilder();
expTree = obj.buildTree(postfix);
ans = expTree.evaluate();
"""
/**
 * This is the interface for the expression tree Node.
 * You should not remove it, and you can define some classes to implement it.
 */

abstract class Node {
    public abstract int evaluate();
    // define your fields here
    protected String val;
    protected Node left;
    protected Node right;
};

class MyNode extends Node {
    public MyNode(String val) {
        this.val = val;
    }

    public int evaluate() {
        if (isNumeric()) {
            return Integer.parseInt(val);
        }
        int leftVal = left.evaluate();
        int rightVal = right.evaluate();
        if (Objects.equals(val, "+")) {
            return leftVal + rightVal;
        }
        if (Objects.equals(val, "-")) {
            return leftVal - rightVal;
        }
        if (Objects.equals(val, "*")) {
            return leftVal * rightVal;
        }
        if (Objects.equals(val, "/")) {
            return leftVal / rightVal;
        }
        return 0;
    }

    public boolean isNumeric() {
        for (char c : val.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }
}

/**
 * This is the TreeBuilder class.
 * You can treat it as the driver code that takes the postinfix input
 * and returns the expression tree represnting it as a Node.
 */

class TreeBuilder {
    Node buildTree(String[] postfix) {
        Deque<MyNode> stk = new ArrayDeque<>();
        for (String s : postfix) {
            MyNode node = new MyNode(s);
            if (!node.isNumeric()) {
                node.right = stk.pop();
                node.left = stk.pop();
            }
            stk.push(node);
        }
        return stk.peek();
    }
};

/**
 * Your TreeBuilder object will be instantiated and called as such:
 * TreeBuilder obj = new TreeBuilder();
 * Node expTree = obj.buildTree(postfix);
 * int ans = expTree.evaluate();
 */
/**
 * 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 {
public:
    virtual ~Node(){};
    virtual int evaluate() const = 0;

protected:
    // define your fields here
    string val;
    Node* left;
    Node* right;
};

class MyNode : public Node {
public:
    MyNode(string val) {
        this->val = val;
    }

    MyNode(string val, Node* left, Node* right) {
        this->val = val;
        this->left = left;
        this->right = right;
    }

    int evaluate() const {
        if (!(val == "+" || val == "-" || val == "*" || val == "/")) return stoi(val);
        auto leftVal = left->evaluate(), rightVal = right->evaluate();
        if (val == "+") return leftVal + rightVal;
        if (val == "-") return leftVal - rightVal;
        if (val == "*") return leftVal * rightVal;
        if (val == "/") return leftVal / rightVal;
        return 0;
    }
};

/**
 * This is the TreeBuilder class.
 * You can treat it as the driver code that takes the postinfix input
 * and returns the expression tree represnting it as a Node.
 */

class TreeBuilder {
public:
    Node* buildTree(vector<string>& postfix) {
        stack<MyNode*> stk;
        for (auto s : postfix) {
            MyNode* node;
            if (s == "+" || s == "-" || s == "*" || s == "/") {
                auto right = stk.top();
                stk.pop();
                auto left = stk.top();
                stk.pop();
                node = new MyNode(s, left, right);
            } else {
                node = new MyNode(s);
            }
            stk.push(node);
        }
        return stk.top();
    }
};

/**
 * Your TreeBuilder object will be instantiated and called as such:
 * TreeBuilder* obj = new TreeBuilder();
 * Node* expTree = obj->buildTree(postfix);
 * int ans = expTree->evaluate();
 */
Try this approach in the editor

Complexity analysis

ApproachTimeSpaceWhen to Use
Stack-Based Tree Construction + Recursive EvaluationO(n)O(n)General case; clean and standard approach for building expression trees from postfix notation
Postorder Recursive Evaluation of TreeO(n)O(h)When the expression tree is already built and only evaluation logic is required

Frequently asked questions

Is Design an Expression Tree With Evaluate Function easy or hard?

The problem is considered Medium difficulty. The main challenge is recognizing that postfix expressions can be converted into an expression tree using a stack and then evaluated with recursion.

Design an Expression Tree With Evaluate Function Python/Java solution

Python, Java, and C++ implementations typically define a Node class with an evaluate() method. The tree is constructed using a stack while iterating through the postfix tokens. Operators combine two popped nodes into a new subtree, while operands create leaf nodes.

How to solve Design an Expression Tree With Evaluate Function in O(n)?

Iterate through the postfix tokens and maintain a stack of nodes. Push number nodes directly. For an operator, pop the right and left operands, create a new operator node, and push it back. After building the tree, evaluate it using a recursive postorder traversal. Both construction and evaluation together remain O(n).

What is the best approach for Design an Expression Tree With Evaluate Function?

The most effective solution builds the expression tree using a stack while scanning the postfix array. Operands are pushed as nodes, while operators pop two nodes and form a new subtree. After construction, the evaluate() method recursively computes results. This approach runs in O(n) time and uses O(n) space.

Is Design an Expression Tree With Evaluate Function asked at Google/Amazon/Meta?

Expression tree construction and evaluation problems commonly appear in interviews at companies like Google, Amazon, and Meta because they test stacks, recursion, and tree design. Variations may involve parsing infix expressions or implementing interpreters.

What data structure is used in Design an Expression Tree With Evaluate Function?

The solution uses a stack for building the tree from postfix notation and a binary tree structure to represent the expression. Each node stores either an operator or operand and references to left and right children.

What is the time complexity of Design an Expression Tree With Evaluate Function?

The overall time complexity is O(n), where n is the number of tokens in the postfix expression. Each token is processed exactly once when constructing the tree, and evaluation visits each node once during recursion.

Comments

Now write it yourselfClose this page and solve Design an Expression Tree With Evaluate Function in the editor, without looking.
Practise Design an Expression Tree With Evaluate Function