Skip to main content

Build Binary Expression Tree From Infix Expression - Solution & Explanation

HardPremiumFree on FleetCodeStringStackTreeBinary Tree4 min readAsked at: Amazon
Practice this problem

Problem Statement

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 2 children) correspond to the operators '+' (addition), '-' (subtraction), '*' (multiplication), and '/' (division).

For each internal node with operator o, the infix expression it represents is (A o B), where A is the expression the left subtree represents and B is the expression the right subtree represents.

You are given a string s, an infix expression containing operands, the operators described above, and parentheses '(' and ')'.

Return any valid binary expression tree, whose in-order traversal reproduces s after omitting the parenthesis from it.

Please note that order of operations applies in s. That is, expressions in parentheses are evaluated first, and multiplication and division happen before addition and subtraction.

Operands must also appear in the same order in both s and the in-order traversal of the tree.

 

Example 1:

Input: s = "3*4-2*5"
Output: [-,*,*,3,4,2,5]
Explanation: The tree above is the only valid tree whose inorder traversal produces s.

Example 2:

Input: s = "2-3/(5*2)+1"
Output: [+,-,1,2,/,null,null,null,null,3,*,null,null,5,2]
Explanation: The inorder traversal of the tree above is 2-3/5*2+1 which is the same as s without the parenthesis. The tree also produces the correct result and its operands are in the same order as they appear in s.
The tree below is also a valid binary expression tree with the same inorder traversal as s, but it not a valid answer because it does not evaluate to the same value.

The third tree below is also not valid. Although it produces the same result and is equivalent to the above trees, its inorder traversal does not produce s and its operands are not in the same order as s.

Example 3:

Input: s = "1+2+3+4+5"
Output: [+,+,5,+,4,null,null,+,3,null,null,1,2]
Explanation: The tree [+,+,5,+,+,null,null,1,2,3,4] is also one of many other valid trees.

 

Constraints:

  • 1 <= s.length <= 100
  • s consists of digits and the characters '(', ')', '+', '-', '*', and '/'.
  • Operands in s are exactly 1 digit.
  • It is guaranteed that s is a valid expression.

Approach Overview

Problem Overview: You receive an infix arithmetic expression as a string containing digits, operators (+, -, *, /), and parentheses. The goal is to convert that expression into a binary expression tree where operators become internal nodes and operands become leaf nodes while preserving operator precedence and parentheses.

The challenge is parsing the infix order correctly. Operators with higher precedence must appear deeper in the tree, and parentheses override normal precedence. A correct solution mimics how compilers parse expressions.

Approach 1: Recursive Split by Lowest Precedence (O(n²) time, O(n) space)

Scan the current substring and locate the operator with the lowest precedence that is not inside parentheses. That operator becomes the root of the current subtree. Recursively build the left subtree from the substring before the operator and the right subtree from the substring after it. Parentheses are handled by tracking depth during the scan. This method mirrors how infix expressions are evaluated but repeatedly rescans substrings, leading to O(n²) worst‑case time complexity. Space complexity is O(n) due to recursion and the resulting binary tree.

Approach 2: Two Stacks (Shunting‑Yard Style) Tree Construction (O(n) time, O(n) space)

The optimal solution processes the expression once using two stacks: one for operand nodes and one for operators. Iterate through the string. When you see a number, create a tree node and push it to the operand stack. When you encounter an operator, resolve any operators on the stack with higher or equal precedence by popping them and forming tree nodes. Parentheses temporarily delay evaluation until the closing parenthesis appears. Each time an operator is resolved, pop two operand nodes, attach them as children, and push the resulting node back.

This method follows the classic infix parsing technique used in compilers. Every character is processed once, and each operator is pushed and popped at most once. The result is O(n) time and O(n) space. The stacks explicitly model expression evaluation order and are typically implemented using a stack data structure.

Recommended for interviews: The stack-based parsing approach is the expected answer. It demonstrates understanding of operator precedence, expression parsing, and tree construction in linear time. Mentioning the recursive split approach first can show conceptual understanding, but implementing the stack-based O(n) solution proves stronger algorithmic skill.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive split by lowest precedenceO(n²)O(n)Good for understanding expression structure or quick prototypes
Two stacks (operator + operand) parsingO(n)O(n)Optimal solution for interviews and production parsing

Video Solution

LeetCode 1597: Build Binary Expression Tree From Infix Expression • AlitaCode • 42 views views

Frequently Asked Questions

Is Build Binary Expression Tree From Infix Expression easy or hard?
Build Binary Expression Tree From Infix Expression is classified as a Hard problem because it combines expression parsing, operator precedence handling, and binary tree construction. Candidates must correctly manage stacks and parentheses while building the tree structure.
Build Binary Expression Tree From Infix Expression Python/Java solution
The Python or Java solution typically uses two stacks. Iterate through the string, push number nodes to an operand stack, and push operators to an operator stack while respecting precedence and parentheses. When resolving an operator, pop two operands, create a new tree node, and push it back.
How to solve Build Binary Expression Tree From Infix Expression in O(n)?
Use a two-stack parsing method similar to the shunting-yard algorithm. Iterate through the expression, pushing operands as tree nodes and managing operators with precedence rules. When an operator with lower precedence appears, resolve the previous operator by forming a subtree. This ensures the entire expression is parsed in linear time.
What is the best approach for Build Binary Expression Tree From Infix Expression?
The most efficient approach uses two stacks: one for operand nodes and one for operators. As you scan the infix expression, numbers become tree nodes and operators are processed according to precedence rules. When resolving an operator, two operand nodes are popped and attached as children. This stack-based parsing builds the tree in O(n) time.
Is Build Binary Expression Tree From Infix Expression asked at Google/Amazon/Meta?
Expression parsing and building trees from infix notation appears in interviews at companies that test compiler-style parsing and stack problems. Variants of this problem have been reported in interviews at companies like Google, Amazon, and other large tech firms focusing on data structures and parsing logic.
What data structure is used in Build Binary Expression Tree From Infix Expression?
The primary data structures are stacks and a binary tree. One stack stores operand nodes, while another stores operators to enforce precedence rules. As operators are processed, nodes are combined to form the final binary expression tree.
What is the time complexity of Build Binary Expression Tree From Infix Expression?
The optimal stack-based solution runs in O(n) time because each character of the expression is processed once and each operator is pushed and popped at most once. Space complexity is O(n) due to the operand stack and the final binary expression tree.

Ready to solve this problem?

Practice Build Binary Expression Tree From Infix Expression with our built-in code editor and test cases.

Practice on FleetCode