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

# Recover a Tree From Preorder Traversal

> Tested Python solution for LeetCode 1028 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 1028, [Hard](/catalog/hard). Topics: [String](/catalog/topics/string), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/description/).

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

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

## Problem

We run a preorder depth-first search (DFS) on the `root` of a binary tree.

At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`.

If a node has only one child, that child is guaranteed to be **the left child**.

Given the output traversal of this traversal, recover the tree and return its `root`.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2024/09/10/recover_tree_ex1.png)

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

![Example 2](https://assets.leetcode.com/uploads/2024/09/10/recover_tree_ex2.png)

```
Input: traversal = "1-2--3---4-5--6---7"
Output: [1,2,5,3,null,6,null,4,null,7]
```

![Example 3](https://assets.leetcode.com/uploads/2024/09/10/recover_tree_ex3.png)

```
Input: traversal = "1-401--349---90--88"
Output: [1,401,null,349,88,90]
```

### Constraints

* The number of nodes in the original tree is in the range `[1, 1000]`.
* `1 <= Node.val <= 10^9`

## Solution

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

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


class Solution:
    # Time: O(n) over the traversal length
    # Space: O(depth) for the node stack
    def recover_from_preorder(self, traversal: str) -> TreeNode[int] | None:
        i = 0
        n = len(traversal)
        stack: list[TreeNode[int]] = []
        while i < n:
            depth = 0
            while i < n and traversal[i] == "-":
                depth += 1
                i += 1
            value = 0
            while i < n and traversal[i].isdigit():
                value = value * 10 + int(traversal[i])
                i += 1
            node: TreeNode[int] = TreeNode(value)
            while len(stack) > depth:
                stack.pop()
            if stack:
                if stack[-1].left is None:
                    stack[-1].left = node
                else:
                    stack[-1].right = node
            stack.append(node)
        return stack[0]
```

## Complexity

| Time | Space |
| - | - |
| O(n) over the traversal length | O(depth) for the node stack |

## Tags

[NeetCode All](/catalog/neetcode).


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