KatInterview

Tree Height Levels: Bottom-Up Node Grouping

Trees & GraphsAuto-graded · 21 test cases
EasyAuto-gradedTrees & Graphstreesbfsheight

Last updated

Compute each node's height in a rooted tree and group nodes by height, testing tree traversal and bottom-up computation.

You receive a tree with n nodes numbered 0 through n - 1. The tree is given as an undirected edge list and a designated root node. Your task is to organize the nodes into levels based on their height, starting from the lowest height and ending at the root.

A node's height is the length of the longest path from that node down to any leaf in its subtree. Group all nodes with the same height together, and return these groups in ascending order of height.

Function Signature

def group_by_height(n: int, edges: list[list[int]], root: int) -> list[list[int]]:

Requirements

  • The tree is rooted at the node specified by root. Each node's children are its neighbors excluding its parent.
  • A node with no children has height 0.
  • A node with children has height equal to 1 + max(height of its children).
  • Return a list of lists where the first list contains all height-0 nodes, the second contains all height-1 nodes, and so on, ending with the root.
  • Within each height group, node labels must be in ascending order.
  • When n = 1, the single node is both root and leaf, so return [[root]].

Constraints

  • 1 <= n <= 100000
  • len(edges) == n - 1
  • Each edge is [a, b] where 0 <= a < n, 0 <= b < n, and a != b
  • The edges form a valid tree (connected, acyclic, no duplicate edges)
  • 0 <= root < n
  • The tree may form a long path, so height can reach n - 1

Examples

Example 1

Input: group_by_height(7, [[0, 1], [0, 2], [1, 3], [1, 4], [2, 5], [5, 6]], 0)

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

Example 2

Input: group_by_height(5, [[0, 3], [3, 4], [2, 0], [1, 0]], 3)

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

Example 3

Input: group_by_height(1, [], 0)

Output: [[0]]

Hints

Hint 1

A node's height is determined by its tallest child, not by its distance from the root

Hint 2

Process nodes bottom-up: children must be evaluated before their parents

Hint 3

Use BFS to establish parent-child relationships, then traverse in reverse to compute heights