Magicsheet logo

Construct Binary Tree from String

Medium
25%
Updated 8/1/2025

Construct Binary Tree from String

What is this problem about?

The Construct Binary Tree from String interview question asks you to parse a string representation of a tree and build the actual object structure. The format typically looks like root(left)(right), where each node value is followed by its children enclosed in parentheses. For example, 4(2(3)(1))(6(5)) represents a tree with 4 at the root.

Why is this asked in interviews?

Meta and Bloomberg often ask the Construct Binary Tree from String coding problem to evaluate string parsing and stack management skills. It tests whether you can handle nested structures and correctly identify which opening parenthesis matches which closing one, which is a fundamental skill in compiler design and data serialization.

Algorithmic pattern used

This utilizes the Depth-First Search, String, Stack, Binary Tree interview pattern.

  1. Recursive approach (DFS): Process the number, then find the substring for the left child (first balanced set of parentheses) and right child (second set), and recurse.
  2. Iterative approach (Stack): Traverse the string. When you see a number, create a node. When you see (, it signals a new child. When you see ), it means the current subtree is finished, so you pop from the stack.

Example explanation

String: 4(2(3)(1))(6)

  1. Current: 4. Create root node 4.
  2. See (. Next is 2. Create node 2 as left child of 4.
  3. See (. Next is 3. Create node 3 as left child of 2.
  4. See ). Node 3 is done.
  5. See (. Next is 1. Create node 1 as right child of 2.
  6. See ). Node 1 is done.
  7. See ). Node 2 is done.
  8. See (. Next is 6. Create node 6 as right child of 4.

Common mistakes candidates make

  • Handling Multi-digit Numbers: Forgetting that node values can be more than one character (e.g., "42") or negative (e.g., "-4").
  • Parenthesis Matching: Failing to correctly identify the boundary of the left child, which can cause the right child's data to be consumed incorrectly.
  • Empty Children: Not handling cases where a child might be missing (e.g., 4()(6)).

Interview preparation tip

Practice using a global index or a pointer when parsing strings recursively. It prevents redundant string slicing and makes the logic for "consuming" characters much cleaner.

Similar Questions