leetcode429.N叉树的层序遍历

题目大意

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

例如,给定一个 3叉树 :
在这里插入图片描述
返回其层序遍历:

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

说明:

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

解题思路

队列,没了。

class Solution {
public:
	vector<vector<int>> levelOrder(Node* root) {
		queue<Node *> que;
		vector<vector<int>> ans;
		if (!root)
		{
			return ans;
		}
		que.push(root);
		while (que.size() != 0)
		{
			auto size = que.size();
			vector<int>res_ans;
			for (auto i = 0; i < size; i++)
			{
				Node * tmp = que.front();
				que.pop();
				res_ans.push_back(tmp->val);
				if ((tmp->children).size() != 0)
				{
					for (auto item : tmp->children)
						que.push(item);
				}
			}
			ans.push_back(res_ans);
		}
		return ans;
	}
};

猜你喜欢

转载自blog.csdn.net/qq_41092190/article/details/106438078