Render an Expression Tree With Only Necessary Parentheses

Last updated: November 29, 2026

Quick Overview

Given a binary expression tree with integer leaves and the operators + - * /, produce its infix string using the fewest parentheses that preserve the tree's meaning under standard precedence and left associativity.

OpenAI
Coding & Algorithms
Software Engineer
OpenAI
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Given a binary expression tree with integer leaves and the operators + - * /, produce its infix string using the fewest parentheses that preserve the tree's meaning under standard precedence and left associativity.

Calculator and code tools in ChatGPT need to show expressions back to users in a readable form, and pretty printers are a common OpenAI screen topic because they reward precise reasoning about precedence. The interviewer is checking that you get the asymmetric right-child rule for subtraction and division correct and test it deliberately.

What the Interviewer Expects
  • Use a precedence table rather than nested conditionals
  • Parenthesize a child only when its precedence is lower than the parent's
  • Apply the extra right-child rule for non-associative operators
  • Recognize that left-associative chains need no parentheses on the left
  • Verify output by evaluating both the tree and the printed string
Key Topics to Cover
binary trees
recursion
operator precedence
associativity
pretty printing
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Add unary minus and exponentiation (right associative): what changes?
  • Parse the printed string back into a tree and check round-trip equality.
  • Simplify the tree (constant folding, x * 1) before printing.
  • Recursion depth: how do you print a tree with 100,000 nodes in a chain?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Leaves hold integers; internal nodes hold + - * / with exactly two children.
  • Standard precedence: * / bind tighter than + -; all four are left associative.
  • Output: infix string with spaces...
High-Level Design

Recurse post-order: render both children, then decide whether each needs parentheses. A left child needs them only if its operator has lower precedence than the parent, because left associativity alre...


Submit Your Answer
Markdown supported