原文链接 [每日 LeetCode] 429. N-ary Tree Level Order Traversal
Description:
Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example, given a 3-ary
tree:
We should return its level order traversal:
[
[1],
[3,2,4],
[5,6]
]
思路:本题和[每日 LeetCode] 102. Binary Tree Level Order Traversal 思想类似,不同之处在于对某个结点的孩子入队时遍历其孩子结点,并以此入队即可。
C++ 代码
/*
// 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)
return {};
vector<vector<int>> res;
queue<Node*> q{{root}};
while(!q.empty()){
vector<int> oneLevel;
for (int i=q.size(); i>0; i--){
Node* t = q.front();
oneLevel.push_back(t->val);
q.pop();
if (!t->children.empty()){
for (auto a : t->children)
q.push(a);
}
}
res.push_back(oneLevel);
}
return res;
}
};
运行时间:156ms
运行时间:34M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于