Skip to content

429. N-ary Tree Level Order Traversal 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  vector<vector<int>> levelOrder(Node* root) {
    if (root == nullptr)
      return {};

    vector<vector<int>> ans;
    queue<Node*> q{{root}};

    while (!q.empty()) {
      vector<int> currLevel;
      for (int sz = q.size(); sz > 0; --sz) {
        Node* node = q.front();
        q.pop();
        currLevel.push_back(node->val);
        for (Node* child : node->children)
          q.push(child);
      }
      ans.push_back(currLevel);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public List<List<Integer>> levelOrder(Node root) {
    if (root == null)
      return new ArrayList<>();

    List<List<Integer>> ans = new ArrayList<>();
    Queue<Node> q = new ArrayDeque<>(List.of(root));

    while (!q.isEmpty()) {
      List<Integer> currLevel = new ArrayList<>();
      for (int sz = q.size(); sz > 0; --sz) {
        Node node = q.poll();
        currLevel.add(node.val);
        for (Node child : node.children)
          q.offer(child);
      }
      ans.add(currLevel);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def levelOrder(self, root: 'Node') -> list[list[int]]:
    if not root:
      return []

    ans = []
    q = collections.deque([root])

    while q:
      currLevel = []
      for _ in range(len(q)):
        node = q.popleft()
        currLevel.append(node.val)
        for child in node.children:
          q.append(child)
      ans.append(currLevel)

    return ans