/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*>q;
if(root!=NULL)q.push(root);
vector<vector<int>>ans;
while(!q.empty()){
int k=q.size();
vector<int>cnt;
while(k--){
TreeNode* p=q.front();
if(p->left!=NULL)q.push(p->left);
if(p->right!=NULL)q.push(p->right);
cnt.push_back(p->val);
q.pop();
}
ans.push_back(cnt);
}
return ans;
}
};
102. 二叉树的层序遍历
最新推荐文章于 2024-12-03 14:49:15 发布