以下代码使用C++实现了代码二叉树的层序遍历。C++二叉树的前序后序遍历都很简答。但是在层序遍历如果去递归一颗树时,可以指定一level(首先求树的深度)。
#include<iostream>
#include<vector>
#include<queue>
#include<unordered_map>
using namespace std;
‘’‘
之前想了一下用递归实现,但是发现没什么思路,然后就使用队列写了。使用queue和vector应该都可以实现的,vector里面有clear方法。
’‘’
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
que.push(root);
vector<int> temp1;
temp1.emplace_back(root->val);
result.emplace_back(temp1);
while (!que.empty()) {
queue<TreeNode*> t_que;
vector<int> temp2;
while (!que.empty()) {
if (que.front()->left!=NULL) {
t_que.push(que.front()->left);
temp2.emplace_back(que.front()->left->val);
}
if (que.front()->right != NULL) {
t_que.push(que.front()->right);
temp2.emplace_back(que.front()->right->val);
}
que.pop();
}
que = t_que;
if (!que.empty()) {
result.emplace_back(temp2);
}
}
return result;
}
public:
vector<vector<int>> result;
};
int main()
{
Solution sol;
TreeNode *root = new TreeNode(1);
TreeNode *n1 = new TreeNode(2);
TreeNode *n2 = new TreeNode(3);
TreeNode *n3 = new TreeNode(4);
TreeNode *n4 = new TreeNode(5);
TreeNode *n5 = new TreeNode(6);
TreeNode *n6 = new TreeNode(7);
TreeNode *n7 = new TreeNode(8);
TreeNode *n8 = new TreeNode(9);
root->left = n1;
root->right = n2;
n1->left = n3;
//n1->right = n4;
n2->left = n5;
//n2->right = n6;
//n3->left = n7;
//n3->right = n8;
vector<vector<int>> result = sol.levelOrder(root);
for (int i = 0;i < result.size(); i++) {
for (int j = 0;j < result[i].size(); j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
system("pause");
}
如果使用递归实现,首先需要计算树的深度,下面的代码直接指定树的深度为3。相应的代码如下所示:
#include<iostream>
#include<vector>
#include<queue>
#include<unordered_map>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
for (int i = 1; i <= 3; i++) {
leveOrder1(root, i);
cout << endl;;
}
return result;
}
void leveOrder1(TreeNode* root, int level) {
if (root==NULL) {
return;
}
if (level==1) {
cout << root->val << " ";
return;
}
leveOrder1(root->left, level-1);
leveOrder1(root->right, level-1);
}
public:
vector<vector<int>> result;
};
int main()
{
Solution sol;
TreeNode *root = new TreeNode(1);
TreeNode *n1 = new TreeNode(2);
TreeNode *n2 = new TreeNode(3);
TreeNode *n3 = new TreeNode(4);
TreeNode *n4 = new TreeNode(5);
TreeNode *n5 = new TreeNode(6);
TreeNode *n6 = new TreeNode(7);
TreeNode *n7 = new TreeNode(8);
TreeNode *n8 = new TreeNode(9);
root->left = n1;
root->right = n2;
n1->left = n3;
//n1->right = n4;
n2->left = n5;
//n2->right = n6;
//n3->left = n7;
//n3->right = n8;
vector<vector<int>> result = sol.levelOrder(root);
for (int i = 0;i < result.size(); i++) {
for (int j = 0;j < result[i].size(); j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
system("pause");
}