LeetCode 429. N叉树的层序遍历(queue)

2021-02-20 14:31:17 浏览数 (1)

1. 题目

代码语言:javascript复制
返回其层序遍历:

[
     [1],
     [3,2,4],
     [5,6]
]

2. 解题

  • queue队列解题
代码语言:javascript复制
/*
// 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>> ans;
        vector<int> lv;
        int Num, i;
        queue<Node*> q;
        q.push(root);
        while(!q.empty())
        {
        	lv.clear();
        	Num = q.size();
        	while(Num--)
        	{
        		lv.push_back(q.front()->val);
        		for(i = 0; i < q.front()->children.size();   i)
        			q.push(q.front()->children[i]);
        		q.pop();
        	}
        	ans.push_back(lv);
        }
        return ans;
    }
};

0 人点赞