【leetcode】429. N-ary Tree Level Order Traversal

problem

429. N-ary Tree Level Order Traversal

solution1:Iteration

/*
// 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) {
        if(root==NULL) return vector<vector<int>>();//
        vector<vector<int>> res;
        queue<Node*> q;
        q.push(root);
        while(!q.empty())
        {
            int size = q.size();
            vector<int> curLevel;
            for(int i=0; i<size; ++i)
            {
                Node* tmp = q.front();
                q.pop();
                curLevel.push_back(tmp->val);
                for(auto a:tmp->children)
                {
                    q.push(a);
                }
            }
            res.push_back(curLevel); 
        }
        return res;
        
    }
};

参考

1. Leetcode_429. N-ary Tree Level Order Traversal;

原文地址:https://www.cnblogs.com/happyamyhope/p/10479233.html