Construct String from Binary Tree
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given the root of a non-empty binary tree, encode it as a string using a pre-order walk: write the node's value, then the left subtree wrapped in parentheses, then the right subtree wrapped in parentheses.
Drop every pair of empty parentheses that is not needed to decode the tree:
- A node with no children is written as just its value.
- A node with only a left child omits the right part: v(left).
- A node with only a right child must keep an empty () for the missing left child: v()(right).
Negative values are written with their minus sign, e.g. -3.
Examples
Constraints
- 1 <= number of nodes <= 10^4
- -1000 <= Node.val <= 1000
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.