Recover a Tree From Preorder Traversal - 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 of this traversal, recover the tree and return its root.
Input & Output
Example 1 — Basic Tree
$
Input:
traversal = "1-2--3--4-5"
›
Output:
[1,2,5,3,4,null,null]
💡 Note:
Root 1 has children 2 and 5. Node 2 has children 3 and 4. The dashes indicate depth: 1 (depth 0), 2 (depth 1), 3 (depth 2), 4 (depth 2), 5 (depth 1).
Example 2 — Single Path
$
Input:
traversal = "1-2--3---4"
›
Output:
[1,2,null,3,null,4]
💡 Note:
Each node has only a left child, creating a left-skewed tree. Node 1 → 2 → 3 → 4 in a single path.
Example 3 — Single Node
$
Input:
traversal = "1"
›
Output:
[1]
💡 Note:
Only root node with value 1, no children.
Constraints
- The number of nodes in the original tree is in the range [1, 1000]
- 1 ≤ Node.val ≤ 109
- The depth of any node is at most 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Format
String with dashes indicating depth and values
2
Parse Structure
Extract depth-value pairs from traversal
3
Build Tree
Construct binary tree using parent-child relationships
Key Takeaway
🎯 Key Insight: Stack depth mirrors tree depth - when moving to shallower levels, pop stack to find correct parent
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code