Recover a Rooted Tree from Depth-Annotated Preorder
GrammarlySoftware Engineer · Technical ScreenLast updated
Reconstruct a general ordered tree from its depth-annotated preorder traversal string and return it as a nested tuple.
Problem Statement
You are given a string traversal representing the preorder traversal of a rooted tree with an arbitrary number of children per node.
In this representation, each node is encoded as a sequence of zero or more hyphens '-' followed by the node's integer value:
- The number of hyphens indicates the depth of the node (0-indexed). The root node has 0 hyphens (depth 0).
- The integer value can contain multiple digits.
- Children of any node appear in their natural left-to-right order immediately following the node in the preorder traversal.
Reconstruct the tree and return it as a canonical nested tuple structure where each node is represented as:
(value, (child_1, child_2, ...))
If a node has no children, its second element must be an empty tuple ().
Function Signature
def recover_tree(traversal: str) -> tuple:
pass
Examples
Example 1
Input: traversal = "1-2--3--4-5"
Output: (1, ((2, ((3, ()), (4, ()))), (5, ())))
Explanation:
- Root is
1(depth 0). 1has children2(depth 1) and5(depth 1).2has children3(depth 2) and4(depth 2).3,4, and5have no children.
Example 2
Input: traversal = "10-20--30-40"
Output: (10, ((20, ((30, ()),)), (40, ())))
Explanation:
- Root is
10. - Node
20has child30. - Node
40is a sibling of20at depth 1.
Constraints
1 <= len(traversal) <= 10^5- Node values are non-negative integers between
0and10^9. - The depth of a node is at most 1 greater than the depth of the node immediately preceding it.
traversalis guaranteed to be non-empty and well-formed according to the rules above.
Hints
Hint 1
Parse the string iteratively by counting consecutive hyphens to determine depth, followed by reading consecutive digits to parse the node value.
Hint 2
Use a stack to maintain the path from the root to the most recently visited node.
Hint 3
Because a node at depth d is always a child of the ancestor at depth d - 1, pop from the stack until its size equals d, then append the new node to the current top.
Follow-up questions
- How would you serialize this nested-tuple tree back into the depth-annotated preorder string?
- How would you modify your solution to validate malformed input, such as depth jumping by more than 1 or leading hyphens before the root?
- If node values could be arbitrary alphanumeric strings with escaped hyphens, how would you adapt your parser?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.