Abstract Syntax Tree Builder - Problem
Build a simple Abstract Syntax Tree (AST) parser for a mini expression language. Your parser should handle:
- Variables: Single letter identifiers (a-z)
- Numbers: Integer literals (0-9)
- Arithmetic: Addition (+), subtraction (-), multiplication (*)
- Function calls: Functions with single arguments like
f(x) - Parentheses: For grouping expressions
The input is a string expression, and you should return the root of the AST as a nested structure. Each node should have a type and appropriate fields (value for literals, left/right for operators, name/arg for functions).
Expression Grammar:
expr := term (('+' | '-') term)*
term := factor (('*') factor)*
factor := number | variable | function | '(' expr ')' Input & Output
Example 1 — Basic Arithmetic
$
Input:
expression = "a + b"
›
Output:
{"type":"operator","value":"+","left":{"type":"variable","value":"a"},"right":{"type":"variable","value":"b"}}
💡 Note:
Simple addition creates an operator node with '+' value, left child 'a' (variable), right child 'b' (variable)
Example 2 — Operator Precedence
$
Input:
expression = "a + b * c"
›
Output:
{"type":"operator","value":"+","left":{"type":"variable","value":"a"},"right":{"type":"operator","value":"*","left":{"type":"variable","value":"b"},"right":{"type":"variable","value":"c"}}}
💡 Note:
Multiplication has higher precedence than addition, so b*c forms a subtree that becomes the right child of the + operator
Example 3 — Function Call
$
Input:
expression = "f(x)"
›
Output:
{"type":"function","name":"f","arg":{"type":"variable","value":"x"}}
💡 Note:
Function call creates a function node with name 'f' and arg pointing to variable node 'x'
Constraints
- 1 ≤ expression.length ≤ 1000
- Expression contains only: a-z, 0-9, +, -, *, (, )
- Expression is guaranteed to be valid
- Function names are single letters
- Numbers are single digits 0-9
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code