Root-to-Leaf Path Metrics on a Weighted Tree
Trees & GraphsAuto-graded · 16 test casesLast 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— thenode_idof this node's parent, or-1if 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:
- root_id — the
node_idof the root. - 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.
- 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_weightequals its weight andmax_depthis0.
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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why a naive solution is slow
If you process each node by scanning the entire input list to find its parent, you perform O(N) work per node, giving O(N²) overall. The fix is to pay the indexing cost once up front so every subsequent lookup is O(1).
Step 1 — Index the tree (two passes, O(N))
The first pass walks the node list to:
- record each node's weight in a hash map (
weights[node_id] = weight), - initialise an empty child list for each node (
children[node_id] = []), - record the root whenever
parent_id == -1.
The second pass attaches every non-root node to its parent's child list. Two passes are necessary because the input is unordered: a child can appear before its parent, so the parent's key must already exist when we try to append to it.
Step 2 — Iterative DFS from the root (O(N))
Push (root_id, weights[root_id], 0) onto an explicit stack. Each iteration pops a frame (node_id, path_weight, depth) and either:
- pushes its children, each with
path_weight + child_weightanddepth + 1, or - updates the answer if the node is a leaf (empty child list).
Answer candidates are updated only at leaves. This is critical for correctness when weights are negative: an internal node is never a path endpoint, so comparing its partial sum against the maximum would be wrong.
The root is pushed with its own weight already included, so by the time a leaf is popped, path_weight holds the exact inclusive root-to-leaf sum.
An explicit stack is used instead of recursion to avoid Python's default recursion limit on deep chains.
Why it is correct
- Root is guaranteed unique by the constraints, so the first pass finds it exactly once.
- Path weight — by induction, every frame holds the sum from the root to that node inclusive. Only leaves produce candidates, so the maximum is over all valid root-to-leaf paths.
- Depth — edges are counted; the root starts at 0, and each hop adds 1. The deepest leaf always has the largest edge count, so updating only at leaves captures
max_depthcorrectly. - All-negative weights —
max_path_weightis initialised toNoneand set on the first leaf encountered, ensuring the result is always an actual path sum rather than an artificial zero. - Single-node tree — the root is immediately a leaf, so
max_path_weight = weightandmax_depth = 0.
Complexity
- Time: O(N). Two linear passes build the index; the DFS visits each node exactly once (one push, one pop).
- Space: O(N). The weight map, child lists (N−1 edges total), and the stack are each proportional to N.
Reference solution
from typing import Dict, List, Tuple
def analyze_execution_tree(nodes: List[List[int]]) -> tuple:
children: Dict[int, List[Tuple[int, int]]] = {}
weights: Dict[int, int] = {}
root_id = -1
# Pass 1: register every node and locate the root.
for node_id, parent_id, weight in nodes:
children[node_id] = []
weights[node_id] = weight
if parent_id == -1:
root_id = node_id
# Pass 2: attach each non-root node to its parent's child list.
for node_id, parent_id, weight in nodes:
if parent_id != -1:
children[parent_id].append((node_id, weight))
# Iterative DFS: each stack frame carries (node_id, path_weight, depth).
max_path_weight = None
max_depth = 0
stack = [(root_id, weights[root_id], 0)]
while stack:
node_id, path_weight, depth = stack.pop()
child_nodes = children[node_id]
if not child_nodes: # leaf node — update answer candidates
if max_path_weight is None or path_weight > max_path_weight:
max_path_weight = path_weight
if depth > max_depth:
max_depth = depth
else:
for child_id, child_weight in child_nodes:
stack.append((child_id, path_weight + child_weight, depth + 1))
return (root_id, max_path_weight, max_depth)
Each child list entry stores (child_id, child_weight) rather than just child_id, so the traversal never needs to call back into the weights map on the hot path — one fewer hash lookup per node.