Build Binary Expression Tree From Infix Expression - Problem
Build Binary Expression Tree From Infix Expression

Imagine you're a compiler engineer tasked with converting mathematical expressions into a tree structure for efficient evaluation! ๐ŸŒณ

A binary expression tree is a special kind of binary tree where:
  • Leaf nodes contain operands (numbers)
  • Internal nodes contain operators (+, -, *, /)
  • Each internal node has exactly two children

Given an infix expression string s containing operands, operators, and parentheses, your goal is to construct a valid binary expression tree that represents this expression.

Key Rules:
  • ๐ŸŽฏ Order of operations matters: parentheses first, then *//, then +/-
  • ๐Ÿ“– In-order traversal of your tree should reproduce the original expression (without parentheses)
  • ๐Ÿ”ข Operands must appear in the same order in both input and tree traversal

For example: "2*3/(2-1)+1" should produce a tree that evaluates correctly following mathematical precedence rules!

Input & Output

example_1.py โ€” Basic Addition
$ Input: s = "2+3"
โ€บ Output: TreeNode('+', TreeNode('2'), TreeNode('3'))
๐Ÿ’ก Note: Simple addition creates a tree with '+' as root and '2', '3' as children. In-order traversal gives '2+3'.
example_2.py โ€” Precedence Example
$ Input: s = "2*3+1"
โ€บ Output: TreeNode('+', TreeNode('*', TreeNode('2'), TreeNode('3')), TreeNode('1'))
๐Ÿ’ก Note: Multiplication has higher precedence than addition, so '2*3' forms the left subtree, then '+' combines it with '1'.
example_3.py โ€” Parentheses Override
$ Input: s = "2*(3+1)"
โ€บ Output: TreeNode('*', TreeNode('2'), TreeNode('+', TreeNode('3'), TreeNode('1')))
๐Ÿ’ก Note: Parentheses force '3+1' to be evaluated first, making it the right subtree of the multiplication.

Visualization

Tap to expand
Expression Tree Construction: "2*3+1"Operand StackOperator StackExpression Tree BuildingTreeNode(1)TreeNode(*,2,3)++*123Step-by-step process:1. Push '2' โ†’ Stack: [2] | 2. Push '*' โ†’ Stack: [2], ['*']3. Push '3' โ†’ Stack: [2,3], ['*'] | 4. See '+': lower precedence, build '*' tree first5. Push '1' and '+' โ†’ Final tree combines (2*3) with 1 using '+'๐ŸŽฏ Key Insight:The stack-based approach naturally handles operator precedence by buildinghigher-precedence operations first, then combining them with lower-precedenceoperations - just like how mathematical expressions are evaluated!Time: O(n) | Space: O(n) - One pass through expression with stack storage
Understanding the Visualization
1
Initialize Stacks
Set up operand stack (for numbers/subtrees) and operator stack (for +,-,*,/,parentheses)
2
Process Operands
When we encounter numbers, create tree nodes and push to operand stack
3
Handle Operators
Compare precedence with stack top - build trees for higher/equal precedence operators first
4
Manage Parentheses
Push '(' to stack, when ')' is found, build trees until we reach the matching '('
5
Final Assembly
Process remaining operators in stack to complete the expression tree
Key Takeaway
๐ŸŽฏ Key Insight: Using two stacks with operator precedence rules allows us to build the expression tree in a single pass, naturally handling the mathematical order of operations while constructing the correct tree structure.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the expression with constant time operations for each character

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Space for operand and operator stacks, plus tree nodes

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค s.length โ‰ค 1000
  • s consists of digits, '+', '-', '*', '/', '(', and ')'
  • Operands are positive integers
  • The expression is guaranteed to be valid
  • No leading zeros in operands
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
24.4K Views
Medium-High Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen