KatInterview

Root-to-Leaf Path Metrics on a Weighted Tree

Trees & GraphsAuto-graded · 16 test cases
MediumAuto-gradedTrees & Graphstrees-graphshash-mapiterative-dfs

Last updated

Tests whether a candidate can traverse an unordered weighted tree in linear time to extract the root, the heaviest root-to-leaf path weight, and the maximum depth.

Problem

You receive an unordered list of nodes belonging to a single weighted tree. Each node is described by a three-element list [node_id, parent_id, weight]:

  • node_id — a unique identifier (32-bit signed integer).
  • parent_id — the node_id of this node's parent, or -1 if the node has no parent (i.e., it is the root).
  • weight — a signed integer cost associated with this node.

Write a function that scans the list and returns a tuple of three integers:

  1. root_id — the node_id of the root.
  2. max_path_weight — the largest cumulative weight along any root-to-leaf path, where the path weight is the sum of every node's weight from the root down to and including the leaf.
  3. max_depth — the number of edges on the longest root-to-leaf path (the root alone has depth 0).

A leaf is any node that has no children.

Notes

  • The input is not sorted in any particular order; a child node may appear before its parent.
  • Weights can be negative. Do not assume a path weight of zero is a valid lower bound.
  • A tree containing only the root counts that node as both root and leaf: max_path_weight equals its weight and max_depth is 0.

Constraints

  • 1 <= len(nodes) <= 100,000
  • -2^31 <= node_id, parent_id <= 2^31 - 1
  • -10^6 <= weight <= 10^6
  • Exactly one node has parent_id == -1.
  • The input always forms a valid, connected, acyclic tree.
  • Your solution must run in O(N) time and use O(N) auxiliary space.

Examples

Example 1

Input: analyze_execution_tree([[10, -1, 5], [20, 10, 3], [30, 10, 8], [40, 20, 7]])

Output: [10, 15, 2]

Example 2

Input: analyze_execution_tree([[5, -1, -10]])

Output: [5, -10, 0]

Hints

Hint 1

Build a lookup structure (hash map) from node_id to its children before you start any traversal — scanning upward through an unsorted list for every node is the trap that makes a solution quadratic.

Hint 2

Because the input is unordered, populate the hash map in two passes: first register every node_id so every key exists, then attach each non-root node to its parent's child list. This avoids missing-key problems when a child appears before its parent.

Hint 3

Use an explicit stack for the traversal instead of recursion, and carry the running path weight and current depth alongside each node. Update your answer candidates only when you reach a leaf (a node with an empty child list), because a node with children is never a leaf — this matters when weights are negative.