Leetcode 764 Solution

This article provides solution to leetcode question 764 (n-ary-tree-level-order-traversal)

https://leetcode.com/problems/n-ary-tree-level-order-traversal

Solution

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        vector<vector<int>> res;
        if (root == NULL)
            return res;

        queue<Node*> q;
        q.push({root});

        while (q.empty() == false)
        {
            int s = q.size();

            vector<int> level_nodes;
            for (int i = 0; i < s; i++)
            {
                auto node = q.front();
                q.pop();

                level_nodes.push_back(node->val);

                for (auto children : node->children)
                    q.push(children);
            }

            res.push_back(level_nodes);
        }

        return res;
    }
};