Magicsheet logo

Construct String from Binary Tree

Medium
25%
Updated 8/1/2025

Construct String from Binary Tree

What is this problem about?

The Construct String from Binary Tree interview question asks you to convert a binary tree into a string format that includes parentheses to preserve the tree structure. The rule is simple: wrap every child subtree in a pair of parentheses. However, there is a specific optimization: you should omit empty parentheses pairs that do not affect the 1-to-1 mapping relationship between the string and the original binary tree.

Why is this asked in interviews?

Meta and Amazon frequently use the Construct String from Binary Tree coding problem to test a candidate's mastery of tree traversals and string formatting. It requires a precise understanding of when a null child is "important" (the left child when a right child exists) versus when it can be ignored (the right child when no right child exists).

Algorithmic pattern used

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

  1. Perform a preorder traversal (Root, Left, Right).
  2. If a node is null, return an empty string.
  3. If a node is a leaf, return its value as a string.
  4. If a node has a right child but no left child, you must include empty parentheses for the left child: Root()(Right).
  5. If a node has only a left child, you can omit the right child's parentheses: Root(Left).

Example explanation

Tree:

    1
   / 
  2   3
   
    4
  1. Start at 1. Append "1".
  2. Move to left child 2. Append "(2".
  3. 2 has no left child but has a right child (4). We must add empty parens for left: "()".
  4. Move to right child 4. Append "(4)".
  5. Close 2's parens: ")".
  6. Move to 1's right child 3. Append "(3)". Result: "1(2()(4))(3)".

Common mistakes candidates make

  • Omitting required empty parens: Forgetting that 1(3) and 1()(3) represent different trees (in the first, 3 is a left child; in the second, it is a right child).
  • Redundant string concatenation: Using standard string addition in a loop (which is O(N^2) in many languages) instead of a StringBuilder or similar buffer.
  • Base case errors: Not correctly identifying leaf nodes, leading to extra empty parentheses like 4()().

Interview preparation tip

Always clarify the rules for "empty" nodes in serialization problems. Tree serialization is a common theme in system design and data storage interviews.

Similar Questions