← Questions

Build a binary tree from a parenthesized string

0
MetaCodingLast asked Jan 2026

A coding interview question asked in Meta's AI-enabled coding round, last asked Jan 2026. It tests trees, parsing and recursion.

A string encodes a binary tree: an integer (possibly negative) followed by zero, one or two subtrees, each in parentheses and encoded the same way. The first pair of parentheses is the left child and the second is the right child. Parse the string into a tree and return its root.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • str_to_tree(s: str) -> TreeNode | None — an empty string returns None.

Example

Trees are shown in level order.

"4(2(3)(1))(6(5))"        ->  [4, 2, 6, 3, 1, 5]

        4
      /   \
     2     6
    / \   /
   3   1 5

"-4(2(3)(1))(6(5)(7))"    ->  [-4, 2, 6, 3, 1, 5, 7]
""                        ->  None

Constraints

  • 0 <= len(s) <= 3 * 10^4.
  • Values fit in a 32-bit integer and may be negative or have several digits.
  • The input is well formed.

Clarifying questions

  • Can values be negative or multi-digit?
  • Can a node have a right child but no left child, and how would that be written (for example 1()(2))?
  • Is the input always well formed, or should errors be reported?

What a strong answer covers

  • Recursive descent with a shared index: read a number, then if the next character is (, parse the left subtree and skip ); do the same for the right subtree.
  • An iterative version with a stack: on a number create a node and attach it to the node on top of the stack (left first, then right), push it; on ) pop.
  • Parsing the number correctly, including the minus sign and multiple digits.
  • O(n) time, O(h) extra space for recursion or the stack.
  • Tests: empty string, single node, negative and multi-digit values, a left-only chain, a deep tree.

Follow-ups

  • Write the reverse: turn a tree into this string, omitting empty parentheses except where needed to mark a missing left child.
  • Report the position of the first error on malformed input.
  • Support an n-ary tree with any number of parenthesized children.

Where it's asked

  • Meta · AI-enabled coding · Last asked Jan 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

trees · parsing · recursion

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