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
INPUTALGORITHMRESULT"a + b * c"Expression String1Tokenize Expression2Parse with Grammar Rules3Handle Operator Precedence4Build AST NodesTokens: [a, +, b, *, c]Grammar: expr → term + term* has higher precedence+a*bcAbstract Syntax TreeProper precedence:a + (b * c)Key Insight:Recursive descent parsing naturally handles operator precedence by mirroringthe expression grammar - deeper recursion levels bind tighter than shallow ones.TutorialsPoint - Abstract Syntax Tree Builder | Tokenization + Recursive Descent
Asked in
Google 45 Microsoft 38 Amazon 32 Apple 28
34.5K Views
Medium Frequency
~35 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