Talentd
FleetCode
Make and follow sheets.Sign in

Construct Binary Tree from String solution and explanation

MediumBinary TreeDepth-First SearchStackString4 min read58.7% acceptanceUpdated 23 Mar 2026Premium elsewhere, free here
leetcode 536 Construct Binary Tree from StringCodebix · 17:05 · 18K viewsWatch on YouTube
9 more videos on this problem
  1. leetcode 536 Construct Binary Tree from StringCodebix · 17:05 · 18K views
  2. 536. Construct Binary Tree from String v2Happy Coding · 12:00 · 5K views
  3. CONSTRUCT BINARY TREE FROM STRING | LEETCODE 536 | PYTHON STACK SOLUTIONCracking FAANG · 16:42 · 4K views
  4. LeetCode 536. Construct Binary Tree from StringHappy Coding · 13:57 · 4K views
  5. Facebook Coding Interview Question | Leetcode 536 | Construct Binary Tree from StringWorkWithGoogler · 21:28 · 2K views
  6. 536. Construct Binary Tree from String (Leetcode Medium)Programming Live with Larry · 15:18 · 380 views
  7. Leetcode 536. Construct Binary Tree from String - locate starts of subtrees and do recursionCode-Yao · 15:15 · 145 views
  8. 536. Construct Binary Tree from StringMuerde un zombie · 14:48 · 88 views
  9. Leetcode: Construct Binary Tree From String (Medium)Lester Minnick · 7:08 · 83 views
  10. Leetcode 536. Construct Binary Tree from String和J一起快乐学算法 · 19:08 · 32 views

The problem

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

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def str2tree(self, s: str) -> TreeNode:
        def dfs(s):
            if not s:
                return None
            p = s.find('(')
            if p == -1:
                return TreeNode(int(s))
            root = TreeNode(int(s[:p]))
            start = p
            cnt = 0
            for i in range(p, len(s)):
                if s[i] == '(':
                    cnt += 1
                elif s[i] == ')':
                    cnt -= 1
                if cnt == 0:
                    if start == p:
                        root.left = dfs(s[start + 1 : i])
                        start = i + 1
                    else:
                        root.right = dfs(s[start + 1 : i])
            return root

        return dfs(s)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode str2tree(String s) {
        return dfs(s);
    }

    private TreeNode dfs(String s) {
        if ("".equals(s)) {
            return null;
        }
        int p = s.indexOf("(");
        if (p == -1) {
            return new TreeNode(Integer.parseInt(s));
        }
        TreeNode root = new TreeNode(Integer.parseInt(s.substring(0, p)));
        int start = p;
        int cnt = 0;
        for (int i = p; i < s.length(); ++i) {
            if (s.charAt(i) == '(') {
                ++cnt;
            } else if (s.charAt(i) == ')') {
                --cnt;
            }
            if (cnt == 0) {
                if (start == p) {
                    root.left = dfs(s.substring(start + 1, i));
                    start = i + 1;
                } else {
                    root.right = dfs(s.substring(start + 1, i));
                }
            }
        }
        return root;
    }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* str2tree(string s) {
        return dfs(s);
    }

    TreeNode* dfs(string s) {
        if (s == "") return nullptr;
        int p = s.find("(");
        if (p == s.npos) return new TreeNode(stoi(s));
        TreeNode* root = new TreeNode(stoi(s.substr(0, p)));
        int start = p;
        int cnt = 0;
        for (int i = p; i < s.size(); ++i) {
            if (s[i] == '(')
                ++cnt;
            else if (s[i] == ')')
                --cnt;
            if (cnt == 0) {
                if (start == p) {
                    root->left = dfs(s.substr(start + 1, i - start - 1));
                    start = i + 1;
                } else
                    root->right = dfs(s.substr(start + 1, i - start - 1));
            }
        }
        return root;
    }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func str2tree(s string) *TreeNode {
	var dfs func(s string) *TreeNode
	dfs = func(s string) *TreeNode {
		if s == "" {
			return nil
		}
		p := strings.IndexAny(s, "(")
		if p == -1 {
			v, _ := strconv.Atoi(s)
			return &TreeNode{Val: v}
		}
		v, _ := strconv.Atoi(s[:p])
		root := &TreeNode{Val: v}
		start := p
		cnt := 0
		for i := p; i < len(s); i++ {
			if s[i] == '(' {
				cnt++
			} else if s[i] == ')' {
				cnt--
			}
			if cnt == 0 {
				if p == start {
					root.Left = dfs(s[start+1 : i])
					start = i + 1
				} else {
					root.Right = dfs(s[start+1 : i])
				}
			}
		}
		return root
	}
	return dfs(s)
}
Try this approach in the editor

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

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.

Comments

Now write it yourselfClose this page and solve Construct Binary Tree from String in the editor, without looking.
Practise Construct Binary Tree from String