KatInterview

Generate Preorder Depth Forest from Directed Node Pairs

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstrees-graphsdepth-first-searchstack

Last updated

Construct a hierarchical forest from directed child-parent relations and output a depth-annotated preorder traversal.

You are given a list of directed structural relationships. Each relation is represented as a pair [child, parent], indicating that child is a direct subordinate of parent.

Your task is to reconstruct the hierarchical forest and output a unified preorder traversal of all trees. Each record in the output must be a two-element list [node_id, depth].

Rules

  1. Roots & Depths: A root is any node that appears in at least one given relation but is never listed as a child. Roots have a depth of 0. Each non-root node has a depth equal to 1 + depth_of_its_parent.
  2. Completeness: Every unique node present across all given pairs must be included in the output exactly once.
  3. Ordering:
    • Primary roots must be processed in ascending numerical order of their IDs.
    • For each tree, conduct a preorder depth-first traversal.
    • Direct children of any node must be visited in ascending numerical order of their IDs.

Constraints

  • 1 <= len(pairs) <= 10**5
  • Each pair consists of exactly two integers [child, parent], where 1 <= child, parent <= 10**9.
  • For each pair, child != parent.
  • Each node appears as a child in at most one pair (i.e., every node has at most one parent).
  • The directed relations form an acyclic forest.
  • Maximum path length from a root to a leaf can be up to len(pairs).

Examples

Example 1

Input: reporting_forest([[2, 1], [3, 1], [4, 2], [5, 6]])

Output: [[1, 0], [2, 1], [4, 2], [3, 1], [6, 0], [5, 1]]

Example 2

Input: reporting_forest([[9, 7], [7, 3], [4, 3]])

Output: [[3, 0], [4, 1], [7, 1], [9, 2]]

Example 3

Input: reporting_forest([[10, 20]])

Output: [[20, 0], [10, 1]]

Hints

Hint 1

Identify root nodes by collecting all unique node IDs and removing any node that acts as a child in any relationship.

Hint 2

Sort the direct children lists for each parent in ascending order.

Hint 3

Because maximum tree depths can be very large (up to 10^5), avoid deep recursion to prevent stack overflow errors. Use an explicit iterative stack for traversal.

Hint 4

When pushing children onto a LIFO stack for a preorder walk, iterate through children in reverse sorted order so the smallest ID is processed first.