LeetCode/solutions/429. N-ary Tree Level Order Traversal.md

43 lines
1.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [429. N-ary Tree Level Order Traversal](https://leetcode.com/problems/n-ary-tree-level-order-traversal/description/)
# 思路
树的层次遍历。和二叉树的层次遍历其实是一样的。
用last指针指向每一层的最后一个节点每当遍历到这个节点即说明遍历完一层
此时应该将此层所有节点用数组a_level记录push进保存最终结果的数组res里然后清空a_level继续遍历下一层。
last初始为root 后面每当遍历完每层最后一个节点后即将last更新成下一层的最后一个节点为此需要用一个next_last来不断记录能确定的下一层的最右节点。
时间复杂度和空间复杂度都是O(n)
(讨论区有一个[运行时间比较短的递归算法](https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/157521/C++-Easy-to-understand-recursive-solution-based-on-DFS-(44-ms-beats-98.67)),但是评论说其复杂度比较高,所以没细看)
# C++
``` C++
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>>res;
if(!root) return res;
queue<Node*>q;
vector<int>a_level;
Node *p, *next_last, *last = root;
q.push(root);
while(!q.empty()){
p = q.front();
q.pop();
a_level.push_back(p -> val);
for(int i = 0; i < p -> children.size(); i++){
next_last = p -> children[i];
q.push(next_last);
}
if(p == last){
res.push_back(a_level);
a_level.clear();
last = next_last;
}
}
return res;
}
};
```