原题链接:Leetcode 429. N-ary Tree Level Order Traversal
Given an n-ary tree, return the level order traversal of its nodes’ values.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: [[1],[3,2,4],[5,6]]
Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
Constraints:
- The height of the n-ary tree is less than or equal to 1000
- The total number of nodes is between [0, 104]
BFS:
思路:
要层序遍历首先就想到BFS,然后就想到使用队列。 先特判是否是空树,否则就将根结点加入队列; 每轮先记录队列中元素的个数cnt,并用一个数组level来表示当前一层的结果。循环cnt次,每次取出元素,将它的值加入level,它的孩子加入队列。
c++代码:
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
if(!root)
return {};
vector<vector<int>> ans;
queue<Node*> q;
q.push(root);
while(!q.empty()){
int cnt = q.size();
vector<int> level;
for(int i = 0; i < cnt; i ++ ){
auto cur = q.front();
q.pop();
level.emplace_back(cur->val);
for(auto child : cur->children){
q.push(child);
}
}
ans.emplace_back(level);
}
return ans;
}
};
复杂度分析:
- 时间复杂度:O(n) 层序遍历刚好每个结点遍历一次
- 空间复杂度:O(n) 为队列需要的空间。最坏情况下所有其他结点都是根结点的孩子,此时队列最多有n-1个元素
|