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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code