力扣 OJ 429. N叉树的层序遍历

题目:

给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。

例如,给定一个 3叉树 :

返回其层序遍历:

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

说明:

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

代码:

class Solution {
public:
	vector<vector<int>> levelOrder(Node* root) {
		vector<int>tmp1;
		vector<Node*>tmp2, tmp3;
		vector<vector<int>>ans;
		if (!root)return ans;
		tmp2.insert(tmp2.end(), root);
		while (!tmp2.empty())
		{
			tmp1.clear();
			int k = tmp2.size();
			while (k--)
			{
				tmp1.insert(tmp1.end(), tmp2[0]->val);
				tmp3 = tmp2[0]->children;
				for (int j = 0; j < tmp3.size(); j++)tmp2.insert(tmp2.end(), tmp3[j]);
				tmp2.erase(tmp2.begin());
			}
			ans.insert(ans.end(),tmp1);
		}
		return ans;
	}
};
发布了1309 篇原创文章 · 获赞 689 · 访问量 174万+

猜你喜欢

转载自blog.csdn.net/nameofcsdn/article/details/104819272