知识点
- vector、queue容器的操作
- 对
vector<int> vec;
做插入元素操作:vec.push_back(x)
。 - 对
queue<TreeNode*> que;
做插入元素操作:que.push(root);
。队列有四个常用的操作:push、pop、front、back,其中,push方法用于在队列的尾部插入一个元素,而pop方法用于移除队列的头部元素。front方法返回队列的第一个元素的引用,而back方法返回队列的最后一个元素的引用。
- 使用auto关键字来自动推断数据类型
for (const auto& level : result) {
for (int val : level) {
cout << val << " ";
}
cout << endl;
}
Leetcode代码:
/**
* 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*> que; // 辅助的队列
vector<vector<int>> result; // 存放最后结果
if(root)
{
que.push(root);
}
while(!que.empty())
{
int size = que.size(); // 每一层的节点个数,也是后面循环的次数
vector<int> vec; // 存放每一层的节点值
for(int i = 0; i < size; i++)
{
TreeNode* tmp = que.front();
que.pop();
vec.push_back(tmp->val);
if(tmp->left)
{
que.push(tmp->left);
}
if(tmp->right)
{
que.push(tmp->right);
}
}
result.push_back(vec);
}
return result;
}
};
ACM模式代码:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
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; // 辅助的队列
vector<vector<int>> result; // 存放最后结果
if (root) {
que.push(root);
}
while (!que.empty()) {
int size = que.size(); // 每一层的节点个数,也是后面循环的次数
vector<int> vec; // 存放每一层的节点值
for (int i = 0; i < size; i++) {
TreeNode* tmp = que.front();
que.pop();
vec.push_back(tmp->val);
if (tmp->left) {
que.push(tmp->left);
}
if (tmp->right) {
que.push(tmp->right);
}
}
result.push_back(vec);
}
return result;
}
};
int main() {
// 测试代码
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20);
root->left->left = new TreeNode(7);
root->left->right = new TreeNode(11);
root->right->left = new TreeNode(15);
root->right->right = new TreeNode(7);
Solution solution;
vector<vector<int>> result = solution.levelOrder(root);
for (const auto& level : result) {
for (int val : level) {
cout << val << " ";
}
cout << endl;
}
return 0;
}
测试用二叉树如下: