mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 429. N-ary Tree Level Order Traversal.md
This commit is contained in:
parent
e6bdd500df
commit
2c830c0cd1
42
429. N-ary Tree Level Order Traversal.md
Normal file
42
429. N-ary Tree Level Order Traversal.md
Normal file
@ -0,0 +1,42 @@
|
||||
# [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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user