题目:
思路:
写过N叉树的层序遍历,(8条消息) LeetCode429.N-Ary-Tree-Level-Order-Traversal<N 叉树的层序遍历>_Eminste的博客-CSDN博客
使用栈保存每一层的结点。然后每次当前层结束。将这一层的值添加进去res中。
代码是:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
if(root==nullptr) return{};
vector<vector<int>> res;
int len = 0;
q.push(root);
while(!q.empty()){
vector<int> level;
len=q.size();
while(len--){
TreeNode* add = q.front();
level.push_back(add->val);
q.pop();
if(add->left!=nullptr) q.push(add->left);
if(add->right!=nullptr) q.push(add->right);
}
res.push_back(level);
}
return res;
}
};