Recover a Tree From Preorder Traversal — LeetCode 1028 Python Solution

HardTreeDepth-First SearchStringBinary Tree
Problem
#1028
Reading time
6 min

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

Example

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

Python solution

Python
from typing import Optional

# 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

def recoverFromPreorder(traversal: str) -> Optional[TreeNode]:
    i = 0
    stack = []  # (node, depth)
    while i < len(traversal):
        depth = 0
        while i < len(traversal) and traversal[i] == '-':
            depth += 1
            i += 1
        val = 0
        while i < len(traversal) and traversal[i].isdigit():
            val = val * 10 + int(traversal[i])
            i += 1
        node = TreeNode(val)
        while stack and stack[-1][1] >= depth:
            stack.pop()
        if stack:
            parent = stack[-1][0]
            if parent.left is None:
                parent.left = node
            else:
                parent.right = node
        stack.append((node, depth))
    return stack[0][0] if stack else None

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1028. Recover a Tree From Preorder Traversal is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1028. Recover a Tree From Preorder Traversal?
LeetCode 1028. Recover a Tree From Preorder Traversal is rated Hard on LeetCode.
What is the time complexity of LeetCode 1028. Recover a Tree From Preorder Traversal?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 1028. Recover a Tree From Preorder Traversal?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 1028. Recover a Tree From Preorder Traversal cover?
LeetCode 1028. Recover a Tree From Preorder Traversal is tagged Tree, Depth-First Search, String and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview