Skip to main content

Construct Binary Tree from String - Solution & Explanation

MediumPremiumFree on FleetCodeStringStackTreeDepth-First Search6 min readAsked at: Amazon, Meta, Bloomberg
Practice this problem

Problem Statement

You need to construct a binary tree from a string consisting of parenthesis and integers.

The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.

You always start to construct the left child node of the parent first if it exists.

 

Example 1:

Input: s = "4(2(3)(1))(6(5))"
Output: [4,2,6,3,1,5]

Example 2:

Input: s = "4(2(3)(1))(6(5)(7))"
Output: [4,2,6,3,1,5,7]

Example 3:

Input: s = "-4(2(3)(1))(6(5)(7))"
Output: [-4,2,6,3,1,5,7]

 

Constraints:

  • 0 <= s.length <= 3 * 104
  • s consists of digits, '(', ')', and '-' only.
  • All numbers in the tree have value at most than 230.

Approach Overview

Problem Overview: You are given a string representing a binary tree where integers denote node values and parentheses describe child relationships. Your task is to parse the string and reconstruct the corresponding binary tree structure. For example, "4(2(3)(1))(6(5))" represents a tree with root 4, left subtree rooted at 2, and right subtree rooted at 6.

Approach 1: Recursive DFS Parsing (O(n) time, O(n) space)

This method walks through the string and recursively builds nodes while tracking the current index. When you read digits (and possible minus signs), you form the node value. If the next character is (, you recursively construct the left child, and if another ( appears afterward, you construct the right child. Each recursive call consumes the portion of the string representing that subtree. Since every character is processed once, the time complexity is O(n). The recursion stack can grow to the tree height, giving O(n) worst-case space for skewed trees. This approach mirrors the natural structure of the tree and is easy to reason about during a depth-first search style reconstruction.

Approach 2: Stack-Based Iterative Construction (O(n) time, O(n) space)

The iterative approach processes the string left to right and uses a stack to maintain the current path of nodes. When you encounter a number, create a new node and attach it as the left child if the parent doesn't have one yet; otherwise attach it as the right child. Push the new node onto the stack. When a closing parenthesis ) appears, it signals the end of a subtree, so you pop the top node from the stack. This method avoids recursion and still visits each character exactly once, producing O(n) time complexity and O(n) auxiliary space for the stack.

The core challenge in this problem is parsing the string while maintaining the correct parent-child relationships in the binary tree. Both methods rely on recognizing that parentheses define subtree boundaries.

Recommended for interviews: The stack-based solution is often preferred because it avoids recursion depth issues and clearly shows how you track the current parent while parsing the string. However, implementing the recursive DFS parser first demonstrates strong understanding of tree structure and recursive decomposition. Most interviewers accept either approach as long as you achieve the optimal O(n) traversal and correctly parse multi-digit values.

Solution

Code

Python

Java

C++

Go

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive DFS ParsingO(n)O(n)When recursion is acceptable and you want a solution that mirrors tree structure naturally
Stack-Based Iterative ConstructionO(n)O(n)Preferred in interviews to avoid recursion depth and explicitly track parent nodes

Video Solution

leetcode 536 Construct Binary Tree from String • Codebix • 18,598 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Construct Binary Tree from String easy or hard?
Construct Binary Tree from String is classified as a Medium problem. The difficulty comes from correctly parsing the string format and maintaining parent-child relationships while handling nested parentheses and multi-digit numbers.
Construct Binary Tree from String Python/Java solution
Python and Java solutions typically implement either recursive DFS parsing with a shared index pointer or an iterative stack-based parser. Both approaches read digits to build node values and attach children when encountering parentheses, achieving O(n) time complexity.
How to solve Construct Binary Tree from String in O(n)?
Scan the string once while constructing nodes as soon as you parse a number. Use either recursion with an index pointer or a stack to track the current parent node. Parentheses define subtree boundaries, allowing you to attach nodes as left or right children during the single pass.
What is the best approach for Construct Binary Tree from String?
The stack-based parsing approach is widely considered the best for interviews. It processes the string from left to right, creates nodes for each number, and uses a stack to track the current parent node. Each closing parenthesis signals the end of a subtree, causing a stack pop. The algorithm runs in O(n) time and O(n) space.
Is Construct Binary Tree from String asked at Google/Amazon/Meta?
Binary tree construction and parsing problems frequently appear in interviews at companies like Amazon, Google, and Meta. Variants involving tree serialization, deserialization, or string-based tree representations test understanding of recursion, stacks, and tree traversal patterns.
What data structure is used in Construct Binary Tree from String?
The main data structures are a binary tree for the final output and either a stack or recursion call stack for parsing. The stack helps maintain the current parent node while processing the parentheses structure in the string.
What is the time complexity of Construct Binary Tree from String?
The optimal time complexity is O(n), where n is the length of the string. Each character is scanned exactly once while building nodes and handling parentheses. Space complexity is also O(n) in the worst case due to the recursion stack or explicit stack used during parsing.

Ready to solve this problem?

Practice Construct Binary Tree from String with our built-in code editor and test cases.

Practice on FleetCode