Tree Traversal with Depth Tracking
Trees & GraphsAuto-graded · 15 test casesLast updated
Tests your ability to perform pre-order depth-first traversal on a tree structure and track hierarchical depth for each node.
You are working with a nested tree structure where each node may have zero or more child nodes. Each node is represented as a dictionary with an id, text, and optionally a replies list containing child nodes in the same format.
Write a function that traverses this tree and produces a flat list of nodes. Each output node should include its original id and text, plus a depth field indicating its level in the hierarchy (roots have depth 0, their children have depth 1, etc.).
The output must follow pre-order traversal: each parent appears before its children, and children appear in their original order.
Input Format
root_comments: A list of dictionaries, each representing a root node- Each node dictionary contains:
"id": a string identifier"text": a string message"replies": (optional) a list of child node dictionaries in the same format
Output Format
Return a list of dictionaries, each containing exactly three keys:
"id": the node's identifier (string)"text": the node's message (string)"depth": the node's nesting level (integer, starting from 0)
Do not include the "replies" key in output dictionaries.
Constraints
- 0 ≤ total number of nodes ≤ 100,000
- 0 ≤ nesting depth ≤ 10,000
- Node IDs are strings but not necessarily unique
- The
"replies"key may be absent or may be an empty list - You must not modify the input structure
Examples
Example 1
Input: flatten_comments([{'id': 'C1', 'text': 'First', 'replies': [{'id': 'C2', 'text': 'Reply', 'replies': [{'id': 'C3', 'text': 'Nested'}]}, {'id': 'C4', 'text': 'Another reply'}]}])
Output: [{'id': 'C1', 'text': 'First', 'depth': 0}, {'id': 'C2', 'text': 'Reply', 'depth': 1}, {'id': 'C3', 'text': 'Nested', 'depth': 2}, {'id': 'C4', 'text': 'Another reply', 'depth': 1}]
Example 2
Input: flatten_comments([])
Output: []
Hints
Hint 1
Consider using an iterative approach with a stack to avoid recursion depth limits on deep chains
Hint 2
Remember that stacks are last-in-first-out: to process children in their original order, push them in reverse
Hint 3
Build new dictionaries for the output rather than mutating the input nodes
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires a pre-order depth-first traversal of a tree structure. Pre-order means visiting each parent before its children, with children processed in their original order.
The most robust approach uses an explicit stack rather than recursion. A stack-based solution avoids Python's recursion depth limit (typically around 1,000 frames), which could be exceeded by deeply nested reply chains.
Algorithm
- Initialize an empty result list and a stack containing all root nodes paired with depth 0
- Push roots in reverse order so the first root is popped first (LIFO behavior)
- While the stack is not empty:
- Pop a (node, depth) pair
- Create a new dictionary with the node's id, text, and current depth, and append it to results
- Get the node's replies (defaulting to an empty list if the key is absent)
- Push all replies onto the stack in reverse order with depth incremented by 1
- Return the flattened list
Why Reverse the Children?
Stacks are last-in-first-out. If we push children in their original order [A, B, C], they pop in reverse order [C, B, A]. To maintain the correct pre-order sequence, we push them reversed so they pop in the original order.
Correctness
- Depth invariant: Each node is pushed with the correct depth. Roots start at 0, and each child receives its parent's depth + 1
- Order invariant: When a node is popped, all its children are pushed on top of any remaining nodes. The entire subtree of the first child is processed before the second child is reached, maintaining pre-order traversal
- Completeness: Every node is pushed exactly once and popped exactly once, ensuring all nodes appear in the output
Complexity
- Time: O(N) where N is the total number of nodes. Each node is visited once with constant-time operations
- Space: O(N) for the output list (unavoidable) plus O(N) worst-case for the stack. In a balanced tree the stack uses O(H × B) where H is height and B is branching factor, but in the worst case (one node with N-1 direct children) the stack holds O(N) items
Edge Cases
- Empty input returns an empty list
- Missing
replieskeys are handled gracefully with.get("replies", []) - Very deep chains (thousands of levels) work correctly with the iterative approach
- The input structure is never modified; new dictionaries are created for output
from typing import Dict, List
def flatten_comments(root_comments: List[Dict]) -> List[Dict]:
flattened = []
stack = [(comment, 0) for comment in reversed(root_comments)]
while stack:
comment, depth = stack.pop()
flattened.append({"id": comment["id"], "text": comment["text"], "depth": depth})
replies = comment.get("replies", [])
stack.extend((reply, depth + 1) for reply in reversed(replies))
return flattened