Recover a Tree From Preorder Traversal Problem
Description
LeetCode Problem 1028.
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.
Example 1:

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

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

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
Approach: Stack of the Current Path
In a preorder traversal, a node's parent is the most recent node one level above it. So while reading the string we keep path, the nodes on the path from the root to the node we just read, where path[d] is the node at depth d.
Read the string one node at a time: count the dashes to get the depth D, then read the digits to get the value (values can have several digits, like 401). Then:
- Cut
pathdown to lengthD. The nodes deeper thanD - 1belong to subtrees we have finished, andpath[D - 1]is now the parent. - Attach the new node to the parent: as the left child if the parent has none yet, otherwise as the right child. This works because preorder visits the left subtree first, and an only child is guaranteed to be a left child.
- Push the new node onto
path.
At the end, path[0] is the root. This is iterative, so it also handles a tree that is one long chain of 1000 nodes.
Complexity: O(n) time, where n is the length of the string, since every node is pushed and popped at most once, and O(h) extra space for the path, where h is the height of the tree.
class Solution:
def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:
path = [] # path[d] is the latest node at depth d, i.e. the path from the root to the last node
i, n = 0, len(traversal)
while i < n:
depth = 0
while traversal[i] == '-':
depth += 1
i += 1
value = 0
while i < n and traversal[i] != '-':
value = value * 10 + int(traversal[i])
i += 1
node = TreeNode(value)
del path[depth:] # the parent is the latest node at depth - 1
if path:
parent = path[-1]
if parent.left is None:
parent.left = node # an only child is always the left one
else:
parent.right = node
path.append(node)
return path[0]