429. N 叉树的层序遍历

429. N 叉树的层序遍历


题目链接:429. N 叉树的层序遍历

代码如下:

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        queue<Node*> que;
        if(root!=nullptr)
            que.push(root);

        vector<vector<int>> result;
		
		//层次遍历
        while(!que.empty())
        {
            vector<int> temp;
            int len=que.size();
            
            for(int i=0;i<len;i++)
            {
                Node *p=que.front();
                que.pop();
                
                temp.push_back(p->val);

                for(int i=0;i<p->children.size();i++)
                {
                    if(p->children[i])
                        que.push(p->children[i]);
                }
            }
            result.push_back(temp);
        }
        return result;    
    }
};

你可能感兴趣的:(leetcode,c++)