层序遍历通过一个 队列实现,循环直到队列为空为止
#include<iostream>
#include<queue>
#include<vector>
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) {
vector<vector<int>>ans;
if (!root)return ans;//空指针检验
queue<TreeNode*>q;
q.push(root);
while (!q.empty()) {
int qsize = q.size();
ans.push_back(vector<int>());
for (int i = 1; i <= qsize; i++) {
auto node = q.front();
q.pop();
ans.back().push_back(node->val);
if (node->left)q.push(node->left);
if (node->right)q.push(node->right);
}
}
return ans;
}
};
int main() {
Solution test;
TreeNode* c = new TreeNode(3);
TreeNode* b = new TreeNode(2, c, nullptr);
TreeNode* a = new TreeNode(1, nullptr, b);
vector<vector<int>>ans = test.levelOrder(a);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[0].size(); j++) {
cout << ans[i][j];
}
}
}