LeetCode N叉树的层序遍历(广度优先搜索)

给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
例如,给定一个 3叉树 :
在这里插入图片描述
返回其层序遍历:

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

说明:

树的深度不会超过 1000。
树的节点总数不会超过 5000。

思路分析:请先翻阅 LeetCode 二叉树的层次遍历
与上一题解法一样,使用广度优先搜索。

/*
// 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) {
    	queue<Node*> myQue;//层次便利辅助队列
        vector<vector<int>> result;
        if (root == NULL){
        	return result;
        }
        else{
        	myQue.push(root);
        }
        while (!myQue.empty()){
        	vector<int> tempRes;//一层的遍历结果
        	int nowQueSize = myQue.size();//当前队列大小
        	//将当前队列中的节点全部向其子节点移动,即当前层移动到下一层
        	for (int index = 0; index < nowQueSize; ++index){
        		root = myQue.front();
        		myQue.pop();
        		tempRes.push_back(root->val);
        		//将该节点的所有子节点入队列
        		for (auto child : root->children){
        			myQue.push(child);
        		}
        	}
        	result.push_back(tempRes);//当前层放入结果集合
        }
        return result;
    }
};

在这里插入图片描述
我也是醉辽,都TM是利用队列的广度优先搜索法,我的这么慢。。。吐血

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/88764315