← Questions
Serialize an expression tree with the fewest parentheses
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Waymo's technical phone screen, last asked Feb 2026. It tests trees, recursion and operator precedence.
Given a binary expression tree whose leaves are numbers or variables and whose internal nodes are the operators +, -, * and /, print it as an infix expression with only the parentheses needed to keep its meaning under normal precedence and left-to-right associativity.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
Node(value: str, left: Node | None = None, right: Node | None = None)— a leaf has no children. -
to_infix(root: Node) -> str— tokens separated by single spaces.
Example
(+ (* a b) c) -> "a * b + c"
(* (+ a b) c) -> "(a + b) * c"
(- a (- b c)) -> "a - (b - c)" # right operand of - at the same level needs them
(- (- a b) c) -> "a - b - c"
(+ a (+ b c)) -> "a + b + c" # + is associative
(/ a (* b c)) -> "a / (b * c)"
Constraints
- Up to 10^4 nodes; the tree may be deep (consider recursion depth).
Clarifying questions
- Which operators, and are there unary ones?
- Is
a + (b + c)allowed to drop its parentheses, or must the output parse back to the same tree shape? - Left-to-right associativity for all operators?
- Spacing rules for the output?
What a strong answer covers
- Precedence levels (
+ -low,* /high) and the two rules: a child needs parentheses if its precedence is lower than the parent's; a right child also needs them at equal precedence when the parent is-or/(non-associative). - The choice for
a + (b + c)anda * (b * c)stated explicitly: drop them for value equality, keep them if the output must round-trip to the same tree. - A post-order recursion returning strings; O(n) time if strings are joined, not repeatedly concatenated.
- An iterative version, or raised recursion limits, for deep trees.
- Tests for each rule, including mixed
-and+on the right.
Follow-ups
- Add right-associative exponentiation
^. - Add unary minus.
- Parse the string back into a tree and check it round-trips.
Where it's asked
- Waymo · Technical phone screen · Last asked Feb 202645 min · Coding: a classic algorithm problem or an original, under-specified problem framed around self-driving
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
