用队列存储,一般存储的是节点的指针。
1、基础版本:
https://blog.csdn.net/FX677588/article/details/74276513
#include<iostream>
#include<queue>
using namespace std;
struct node{
int val;
struct node*left;
struct node*right;
node(int v):val(v),left(nullptr),right(nullptr){
};
};
void Level1(struct node *p)
{
queue<node*>q;
q.push(p);
while (!q.empty()){
node *tmp = q.front();
q.pop();
cout<<tmp->val<<" ";
if (tmp->left)q.push(tmp->left);
if (tmp->right)q.push(tmp->right);
}
}
int main()
{
struct node *BT[6];
BT[0] = new node(0);
BT[1] = new node(1);
BT[2] = new node(2);
BT[3] = new node(3);
BT[4] = new node(4);
//BT[5] = new node(5);
//BT[0]->left = BT[1]; BT[0]->right = BT[2]; BT[1]->left = BT[3]; BT[1]->right = BT[4]; BT[2]->left = BT[5];
BT[0]->left = BT[1]; BT[0]->right = BT[2]; BT[2]->left = BT[3]; BT[2]->right = BT[4];//BT[3]->right = BT[4];
Level1(BT[0]);
cout<<endl;
return 0;
}
2、leetcode:https://leetcode.com/problems/binary-tree-level-order-traversal/
将结果存在二维数组中。需要记录每一层的的数量结束标记。
vector<vector<int> > Level2(struct node *p)
{
vector<vector<int> >res;
if (p==nullptr)
{
return res;
}
queue<node*>q;
q.push(p);
int count = 1;
vector<int>level;
while(!q.empty())
{
struct node * tmp = q.front();
q.pop();
int t = tmp->val;
level.push_back(t);
if (tmp->left)q.push(tmp->left);
if (tmp->right)q.push(tmp->right);
count--;
if (count==0)
{
count = q.size();
res.push_back(level);
level.clear();
}
}
return res;
}
- 在(1)的基础上改进,让输出的形式中带有NULL。
void Level3(struct node *p)
{
if (p==nullptr)return;
queue<node*>q;
q.push(p);
int count = 1;
int cnt_null = 0;
int tmp_cnt = 1;
while (!q.empty()){
node * tmp = q.front();
q.pop();
if (tmp==NULL){
cout<< "NULL ";
continue;
}
else {
cout<<tmp->val<<" ";
}
count--;
if ((tmp->left)==NULL)cnt_null++;
if ((tmp->right)==NULL)cnt_null++;
q.push(tmp->left);
q.push(tmp->right);
if (count==0)
{
if (cnt_null==2*tmp_cnt)break; // 如果当前节点NULL的个数是节点个数的2倍,那说明以及到达终点了。
//cout<<"cnt_null: "<<cnt_null<<" "<<"tmp_cnt: "<<tmp_cnt<<endl;
tmp_cnt = q.size()-cnt_null;
count = q.size()-cnt_null;
cnt_null = 0;
}
}
}