Leetcode #1028: Recover a Tree From Preorder Traversal
In this guide, we solve Leetcode #1028 Recover a Tree From Preorder Traversal in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Tree, Depth-First Search, String, Binary Tree
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: traversal = "1-2--3--4-5--6--7"
Output: [1,2,5,3,4,6,7]
Python Solution
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
The time complexity is O(V+E). The space complexity is O(V).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.