429. N-ary Tree Level Order Traversal
MediumView on LeetCode
Time: O(n)
Space: O(n)
Advertisement
Intuition
BFS level-by-level, same as binary tree but each node can have multiple children.
Algorithm
- 1Start BFS queue with root.
- 2For each level: record count of nodes in queue, dequeue that many nodes collecting their values, enqueue all their children.
- 3Append each level's values to result.
Example Walkthrough
Input: root=[1,[3,2,4],[5,6]]
- 1.Level 0: [1].
- 2.Level 1: [3,2,4].
- 3.Level 2: [5,6].
Output: [[1],[3,2,4],[5,6]]
Common Pitfalls
- •Snapshot the queue size before processing each level, otherwise newly added children corrupt level count.
429.cs
C#
// Approach: BFS with a queue; collect all children of dequeued nodes
// at each level into the next level’s snapshot.
// Time: O(n) Space: O(n)
public class Node
{
public int val;
public IList<Node> children;
public Node() { }
public Node(int _val)
{
val = _val;
}
public Node(int _val, IList<Node> _children)
{
val = _val;
children = _children;
}
}
public class Solution
{
public IList<IList<int>> LevelOrder(Node root)
{
if (root == null)
return new List<IList<int>>();
IList<IList<int>> ans = new List<IList<int>>();
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count > 0)
{
IList<int> currLevel = new List<int>();
int sz = q.Count;
for (int i = 0; i < sz; i++)
{
Node node = q.Dequeue();
currLevel.Add(node.val);
foreach (Node child in node.children)
q.Enqueue(child);
}
ans.Add(currLevel);
}
return ans;
}
}Advertisement
Was this solution helpful?