Problem 494445 · medium · Phase 04 Non-Linear Data Structures

Reporting Lines by Level

n-ary tree · BFS · queue

An org chart is an N-ary tree of Node objects (val is an employee id, children is a list of direct reports in seniority order). Return a list of levels: the first level holds the root, the second holds all direct reports of the root from left to right, and so on. Return [] for an empty chart.

Examples

Input:  root = Node(1, [Node(2, [Node(5), Node(6)]), Node(3), Node(4, [Node(7)])])
Output: [[1], [2, 3, 4], [5, 6, 7]]

Input:  root = Node(9)
Output: [[9]]

Constraints

  • 0 <= number of nodes <= 10**4
  • Target: O(n) time; use a real queue (deque), not list.pop(0)

Goals

  • Group the nodes of an N-ary tree by depth with a queue
  • Process one whole level per outer iteration
Starting Python…