KatInterview

Tree Traversal with Depth Tracking

Trees & GraphsAuto-graded · 15 test cases
EasyAuto-gradedTrees & Graphstree-traversaldfsdepth-tracking

Last 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