Label Each Node as Root, Inner, or Leaf from Parent Links
Trees & GraphsAuto-graded · 22 test casesLast updated
Classify every node of a rooted tree given as [id, parent_id] pairs into Root, Inner, or Leaf, using a set of parent ids, and return the labels sorted by id.
Label Tree Nodes
A rooted tree is described by a list of edges-to-parent records. Each record is a two-element list [id, parent_id]:
idis the unique integer identifier of a node.parent_idis the identifier of that node's parent, orNoneif the node has no parent.
Write a function that assigns exactly one label to every node:
"Root"if the node has no parent (parent_idisNone). This rule takes priority: a root is always labeled"Root", even if it has children, and even if it is the only node."Inner"if the node has a parent and at least one other node lists it as its parent."Leaf"if the node has a parent and no node lists it as its parent.
Return a list of [id, label] pairs, one per node, sorted by id in ascending order. The input records may be given in any order.
Constraints
- The number of nodes is between 1 and 100,000.
- Every
idis unique, and each node has at most one parent. - The input is a valid tree with exactly one root.
- Labels are exactly the strings
"Root","Inner", and"Leaf"(case-sensitive).
Examples
Example 1
Input: label_tree_nodes([[1, None], [2, 1], [3, 1], [4, 2], [5, 2]])
Output: [[1, 'Root'], [2, 'Inner'], [3, 'Leaf'], [4, 'Leaf'], [5, 'Leaf']]
Example 2
Input: label_tree_nodes([[1, None]])
Output: [[1, 'Root']]
Hints
Hint 1
A node has a child exactly when its id shows up as somebody's parent_id. How can you collect all such ids for fast lookup?
Hint 2
Check the Root condition before anything else, so a root that has children is never labeled Inner and a lone root is never labeled Leaf.
Hint 3
Do not forget the output order: sort the final [id, label] pairs by id, since the input may be unordered.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A node's label depends on two facts: whether it has a parent, and whether it has a child.
- Build a set of every non-
Noneparent_id. An id is in this set exactly when at least one node has it as a parent, i.e. it has a child. - Go through each record and decide the label in a fixed order:
parent_idisNone->"Root".- otherwise,
idis in the parent set ->"Inner". - otherwise ->
"Leaf".
- Sort the resulting
[id, label]pairs byid.
Why it is correct
The three cases are mutually exclusive and cover every node, so each node gets exactly one label. Testing for Root first guarantees that a root with children is not mislabeled "Inner", and that a single-node tree gives "Root" rather than "Leaf". For non-root nodes, membership in the parent set is equivalent to having a child, which separates Inner from Leaf. Sorting at the end makes the output independent of input order.
Complexity
With n records: building the set is O(n), labeling is O(n), and sorting is O(n log n). Total time is O(n log n); space is O(n).
Reference solution
from typing import List, Optional
def label_tree_nodes(records: List[List[Optional[int]]]) -> List[List[object]]:
# Ids that appear as someone's parent have at least one child.
parents_seen = {p for _, p in records if p is not None}
result = []
for node_id, parent_id in records:
if parent_id is None:
label = "Root"
elif node_id in parents_seen:
label = "Inner"
else:
label = "Leaf"
result.append([node_id, label])
result.sort(key=lambda row: row[0])
return result