Leetcode

N-ary Tree Level Order Traversal

  • Time:O(n)
  • Space:O(n)

C++

class Solution {
 public:
  vector<vector<int>> levelOrder(Node* root) {
    if (!root)
      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;
  }
};

JAVA

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<>(Arrays.asList(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;
  }
}