Skip to main content
Back to problems
#429
Medium Algorithms

N ary tree level order traversal

Tree Breadth-First Search
71.5% acceptance
Jan 13, 2026
3744
145
Given an n-ary tree, return the level order traversal of its nodes' values.

Solution

C++
Time O(n²)
Space O(1)
LeetCode
solution.cpp
class Solution {
public:
  vector<vector<int>> levelOrder(Node* root) {
    if (!root) return {};
    vector<vector<int>> result;
    queue<Node*> q;
    q.push(root);
    while (!q.empty()) {
      int sz = q.size();
      vector<int> level;
      for (int i = 0; i < sz; i++) {
        Node* node = q.front(); q.pop();
        level.push_back(node->val);
        for (Node* child : node->children)
          q.push(child);
      }
      result.push_back(level);
    }
    return result;
  }
};