一,题目描述
二,解题思路:
广度优先遍历:使用队列
三,代码实现
/**
* 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) {}
* };
*/
#include<queue>
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> vv;
queue<TreeNode*> qu;
if(root != nullptr)
{
qu.push(root);
}
while(!qu.empty())
{
vector<int> v;
TreeNode* ptr = nullptr;
int num = qu.size();
for(int i=0; i<num; i++)
{
ptr = qu.front();
v.push_back(ptr->val);
qu.pop();
if(ptr->left != nullptr) { qu.push(ptr->left); }
if(ptr->right != nullptr) { qu.push(ptr->right); }
}
vv.push_back(v);
}
return vv;
}
};