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
Recover Tree From Preorder Traversal INPUT traversal = "1-2--3--4-5" Parsed Elements: 1 D=0 -2 D=1 --3 D=2 --4 D=2 -5 D=1 D = Depth (dash count) Structure Hint: Root has depth 0 Children: depth + 1 One child = left child Input String: "1-2--3--4-5" ALGORITHM STEPS 1 Parse String Count dashes for depth Extract node values 2 Use Stack Stack tracks path from root to current node 3 Find Parent Pop stack until size equals current depth 4 Attach Node Left child first, then right child if exists Stack Simulation: 1 2 3 Stack after processing "3" 1 5 Stack after processing "5" FINAL RESULT Recovered Binary Tree: 1 2 5 3 4 D=0 D=1 D=2 Tree Structure: 1 is root, 2 and 5 are children 3 and 4 are children of 2 Output (Level Order): [1,2,5,3,4,null,null] Key Insight: The stack size always equals the depth of the current path. When processing a node at depth D, pop the stack until its size equals D. The stack top is then the parent. Attach as left child if empty, otherwise as right child. Time: O(n), Space: O(h) where h is tree height. TutorialsPoint - Recover a Tree From Preorder Traversal | Optimal Stack-Based Approach
Asked in
Facebook 25 Google 20 Amazon 15
67.0K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen