Expression Tree Evaluator - Problem

Given an infix mathematical expression as a string, build an expression tree and evaluate it to return the final result.

The expression contains:

  • Single-digit integers (0-9)
  • Four operators: +, -, *, /
  • Parentheses ( and ) for grouping

Follow standard operator precedence: * and / have higher precedence than + and -. Operations of the same precedence are evaluated left to right.

Return the evaluated result as an integer (truncate any decimal part).

Input & Output

Example 1 — Basic Arithmetic
$ Input: expression = "3+2*4"
Output: 11
💡 Note: Following precedence: 2*4 = 8, then 3+8 = 11. The multiplication is evaluated first due to higher precedence.
Example 2 — Parentheses Override
$ Input: expression = "(3+2)*4"
Output: 20
💡 Note: Parentheses change precedence: (3+2) = 5, then 5*4 = 20. Addition is evaluated first due to parentheses.
Example 3 — Division with Truncation
$ Input: expression = "7/2+1"
Output: 4
💡 Note: Division first: 7/2 = 3 (truncated), then 3+1 = 4. Integer division truncates the decimal part.

Constraints

  • 1 ≤ expression.length ≤ 1000
  • expression consists of digits 0-9, operators +, -, *, /, and parentheses ( )
  • All intermediate calculations fit in a 32-bit integer
  • Division truncates toward zero

Visualization

Tap to expand
INPUT EXPRESSIONInfix Expression3 + 2 * 4Standard mathematical notationwith operator precedence rulesParse Requirements:• Respect precedence (* before +)• Handle parentheses correctly• Support all four operatorsTREE CONSTRUCTION+3*241234Post-order traversal stepsHigher precedence = deeper nodesEVALUATION RESULTComputation Steps2 * 4 = 83 + 8 = 11Final Result11Tree evaluation naturally handlesoperator precedence throughrecursive post-order traversalKey Insight:Expression trees naturally encode operator precedence by structure.Higher precedence operators become deeper nodes, ensuring they evaluate firstduring post-order traversal, eliminating the need for explicit precedence checking.TutorialsPoint - Expression Tree Evaluator | Recursive Descent Parser
Asked in
Google 45 Microsoft 38 Amazon 32 Apple 28
78.0K Views
Medium Frequency
~25 min Avg. Time
2.2K 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