Tree Height Levels: Bottom-Up Node Grouping
Trees & GraphsAuto-graded · 21 test casesLast 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 <= 100000len(edges) == n - 1- Each edge is
[a, b]where0 <= a < n,0 <= b < n, anda != 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
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to group nodes by their height in the tree. Height is defined as the maximum number of edges from a node down to any leaf in its subtree. This is different from depth, which measures distance from the root.
The solution uses two passes:
-
Root the tree and track parent relationships: Run BFS starting from the given root. This establishes which nodes are children of which parents. The BFS order has a key property: every node appears after its parent in the traversal sequence.
-
Calculate heights bottom-up: Process the BFS order in reverse. This ensures we visit every child before visiting its parent. For each node, propagate its height upward: if a node has height
h, it contributesh + 1to its parent's height (if that's larger than the parent's current height). Nodes with no children keep height0.
After computing all heights, we bucket nodes by their height value. Since we iterate through node labels in increasing order (0 to n-1), each bucket is automatically sorted.
Why It Works
-
Heights are computed correctly: By processing in reverse BFS order, every child has been evaluated before we compute its parent's height. A parent's height becomes
1 + max(child heights), exactly matching the definition. -
No missing height levels: The path from root to its deepest leaf includes nodes at every height from
height[root]down to0, so no bucket remains empty. -
The last group contains only the root: All other nodes are descendants and must have strictly smaller heights than the root.
-
Handles edge cases: A single-node tree has the root at height
0. Trees shaped like long paths (up ton-1edges deep) are handled iteratively without recursion issues.
Complexity
- Time: O(n) — building the adjacency list, BFS traversal, reverse pass, and bucketing all take linear time
- Space: O(n) — for the adjacency list, parent array, seen flags, height array, and output structure
Solution Code
def group_by_height(n: int, edges: list[list[int]], root: int) -> list[list[int]]:
# Build adjacency list from undirected edges
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
# BFS from root to establish parent relationships
parent = [-1] * n
order = [root]
seen = [False] * n
seen[root] = True
for u in order:
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
order.append(v)
# Compute heights by processing nodes bottom-up
height = [0] * n
for u in reversed(order):
p = parent[u]
if p >= 0 and height[u] + 1 > height[p]:
height[p] = height[u] + 1
# Group nodes by height
levels = [[] for _ in range(height[root] + 1)]
for v in range(n):
levels[height[v]].append(v)
return levels