KatInterview

Label Each Node as Root, Inner, or Leaf from Parent Links

Trees & GraphsAuto-graded · 22 test cases
EasyAuto-gradedTrees & Graphstreehash-setclassification

Last 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]:

  • id is the unique integer identifier of a node.
  • parent_id is the identifier of that node's parent, or None if the node has no parent.

Write a function that assigns exactly one label to every node:

  • "Root" if the node has no parent (parent_id is None). 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 id is 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.