N-ary Tree Level Order Traversal N叉树的层次遍历

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        queue<Node*> q;
        vector<vector<int>> vec;
        if(!root) return vec;
        q.push(root);
        while(!q.empty()) {
            vector<int> tmp;
            for(int size=q.size();size;--size) {
                Node* node=q.front();q.pop();
                tmp.push_back(node->val);
                for(auto& child:node->children) q.push(child);
            }
            vec.push_back(tmp);
        }
        return vec;
    }
};

 

posted @ 2020-03-16 12:18  qiujiejie  阅读(100)  评论(0编辑  收藏  举报