Recover a Tree From Preorder Traversal

Parse depth-prefix tokens; maintain a stack of ancestors and attach each node to its parent at depth-1.

Hard
Time O(n) Space O(h)
LeetCode
4 min read
tree parsing stack

Problem#

A binary tree is preorder-serialized as: each node is preceded by d dashes where d is its depth (the root has zero dashes). Reconstruct and return the tree.

Examples#

  • "1-2--3--4-5--6--7"[1,2,5,3,4,6,7]
  • "1-2--3---4-5--6---7"[1,2,5,3,null,6,null,4,null,7]

Constraints#

  • 1 <= S.length <= 10^4.

Approach#

Tokenize on the fly. Maintain a stack of nodes representing the current root-to-node spine. For each token at depth d, pop until the stack’s size equals d; the new node is the next child of the stack top — left first then right.

Solution#

Recover a Tree From Preorder Traversal
class Solution {
public:
TreeNode* recoverFromPreorder(string traversal) {
vector<TreeNode*> stack;
int i = 0, n = traversal.size();
while (i < n) {
int depth = 0;
while (i < n && traversal[i] == '-') { ++depth; ++i; }
int val = 0;
while (i < n && isdigit(traversal[i])) {
val = val * 10 + (traversal[i] - '0');
++i;
}
TreeNode* node = new TreeNode(val);
while ((int)stack.size() > depth) stack.pop_back();
if (!stack.empty()) {
if (!stack.back()->left) stack.back()->left = node;
else stack.back()->right = node;
}
stack.push_back(node);
}
return stack.front();
}
};

Editorial#

The stack represents the current ancestor chain. At depth d, the parent is at index d - 1; popping back to size d ensures that. Left-first attachment matches preorder consumption — the right child only fills after the entire left subtree is emitted.

Complexity#

  • Time: O(n).
  • Space: O(h).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.