> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Construct Binary Tree from String

> Tested Python solution for LeetCode 536 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 536, [Medium](/catalog/medium). Topics: [Stack](/catalog/topics/stack), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [String](/catalog/topics/string), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/construct-binary-tree-from-string/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 536   # by problem number
lcpy gen -s construct_binary_tree_from_string   # by problem name
```

## 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.

### Examples

![Example 1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0536.Construct%20Binary%20Tree%20from%20String/images/butree.jpg)

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

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

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

### Constraints

* 0 \<= s.length \<= 3 \* 10^4
* s consists of digits, '(', ')', and '-' only.
* All numbers in the tree have value at most than 2^30.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/construct_binary_tree_from_string/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/construct_binary_tree_from_string/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Time: O(n)
    # Space: O(h) for the recursion stack, where h is the tree height
    def str2tree(self, s: str) -> TreeNode[int] | None:
        if not s:
            return None

        def parse(i: int) -> tuple[TreeNode[int], int]:
            start = i
            if s[i] == "-":
                i += 1
            while i < len(s) and s[i].isdigit():
                i += 1
            node = TreeNode(int(s[start:i]))
            if i < len(s) and s[i] == "(":
                node.left, i = parse(i + 1)
                i += 1  # closing paren of the left subtree
                if i < len(s) and s[i] == "(":
                    node.right, i = parse(i + 1)
                    i += 1  # closing paren of the right subtree
            return node, i

        root, _ = parse(0)
        return root
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(h) for the recursion stack, where h is the tree height |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.