题目
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*> que;
if(root != nullptr) que.push(root);
vector<vector<int>> result;
while(!que.empty())
{
int size = que.size();
vetor<int> vec;
for(int i = 0; i < size; i++)
{
TreeNode* node = que.front();
que.pop();
vec.push_back(node->val);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
result.push_back(vec);
}
return result;
}
};
网友评论