二叉樹的層次遍歷,利用隊列輔助實習,並且使用last和nlast 實現二叉樹的分層,隊列用的是stl裏面的。核心點是用隊列輔助實現層次遍歷,也就是廣度優先遍歷,判斷何時分層,當隊列中的最後一個節點和隊首元素相等的時候代表着一層結束了,也就是代碼中的last和nlast相等的時候了,然後再讓nlast指向現在的隊尾元素直到下一次last和nlast相等也就是說nlast一直記錄的是每一層的最後一個數字。直到最後一個元素彈出。
測試樣例:1230048000500
輸入樹的形狀:
1
2 5
3 4
8
代碼:
#include <cstdlib>
#include <iostream>
#include <queue>
//size查看數目
//empty判空
//front 取隊首
//back取隊尾
//pop出棧
using namespacestd;
struct Node {
int data ;
structNode* left;
structNode* right;
};
struct Node * Create(){//構建二叉樹
int x;
structNode* tree;
tree=(structNode*)malloc(sizeof(structNode));
cin>>x;
if (x==0) {
tree=NULL;
}
else{
tree->data=x;
tree->left=Create();
tree->right=Create();
}
return tree;
}
void print(structNode* tree){//將二叉樹放入的一個隊列中
queue<structNode*> q1;//創建一個隊列用來存放節點
q1.push(tree);//首先將樹的根節點放入
int last=-1;//定義兩個數分別指向出棧的數字和隊列中的最後一個數字
int nlast=tree->data;
while (!q1.empty()) {
last=q1.front()->data;//last指向隊首元素
if (q1.front()->left!=NULL) {//判讀左子樹是否爲空不爲空的話加入到隊列中
q1.push(q1.front()->left);
}
if (q1.front()->right!=NULL) {//判斷右子樹是否爲空如果不爲空加入到隊列中
q1.push(q1.front()->right);
}
if (nlast==last) {//判斷nlast和last是否相同如果相同就是這一層的最後一個輸出換行
nlast=q1.back()->data;
cout<<q1.front()->data<<endl;
}
else{//不相同就輸出數字和空格
cout<<q1.front()->data;
}
q1.pop();//出棧一個節點
}
}
int main()
{
structNode* tree;
tree=Create();
print(tree);
}
輸出結果:
1
25
34
8