The Recover a Tree From Preorder Traversal problem gives you a preorder traversal string encoding of a binary tree where dashes (—) indicate the depth. Parse this string to reconstruct the tree. This hard coding problem uses DFS with a stack to parse depth-encoded nodes. The DFS, string, binary tree, and tree interview pattern is the core.
Microsoft, Meta, Amazon, Google, and Bloomberg ask this because it tests tree construction from a serialization format — a skill relevant to data persistence and network transmission. The depth-stack parsing is a clean DFS construction approach.
DFS with depth stack. Parse the string left to right. For each node: count leading dashes (= depth), parse the number after dashes. Maintain a stack representing the current path from root. Pop the stack until its size equals the current node's depth, then attach as the left or right child of stack[-1]. Push current node.
s="1-2--3---4-5--6---7".
Tree reconstruction from depth-encoded strings uses a depth-indexed stack. The stack always contains the path from root to the current deepest node. When encountering a new node at depth d, pop the stack until depth == d (the parent is now at the top). Practice tree serialization/deserialization in multiple formats: preorder with nulls, level-order, depth-encoded.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Step-By-Step Directions From a Binary Tree Node to Another | Medium | Solve | |
| Construct String from Binary Tree | Medium | Solve | |
| Construct Binary Tree from String | Medium | Solve | |
| Smallest String Starting From Leaf | Medium | Solve | |
| Sum Root to Leaf Numbers | Medium | Solve |