利用队列实现层序遍历
关于二叉树其他的基本操作可以看我前几篇文章:
二叉树的基本操作:二叉树的后序遍历非递归算法
基础知识:
直接调用C++内部的queue
要有头文件 #include
队列的基本操作:
定义一个queue的变量 queue Q
查看是否为空范例 Q.empty() 是的话返回1,不是返回0;
从已有元素后面增加元素 Q.push()
输出现有元素的个数 Q.size()
返回第一个元素 Q.front()
显示最后一个元素 Q.back()
清除第一个元素 Q.pop()
程序执行时,输入
ABDH##I##E##CF#J##G##
创建如图所示的二叉树
代码如下:
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
typedef char datatype;
//二叉树的左右链表示,也叫做二叉链表表示
typedef struct node {
datatype data;
struct node* lchild;
struct node* rchild;
}Node;
typedef Node* Btree;
//创建新的结构体list,包含Btree和int,来帮助实现后序非递归算法
typedef struct list {
Btree ptr;
int flag;
}List;
Btree preCreateBT() {
Btree T;
char ch;
cin >> ch;
if (ch == '#') {
T = NULL;
}
else {
T = new node;
T->data = ch;
T->lchild = preCreateBT();
T->rchild = preCreateBT();
}
return T;
}
//先序遍历
/*
void PreOrder(Btree BT) {
if (BT != NULL) {
cout << BT->data<<endl;
PreOrder(BT->lchild);
PreOrder(BT->rchild);
}
}
*/
//中序遍历
/*
void InOrder(Btree BT) {
if (BT != NULL) {
InOrder(BT->lchild);
cout << BT->data << endl;
InOrder(BT->rchild);
}
}
*/
//后序遍历
/*
void PostOrder(Btree BT) {
if (BT != NULL) {
PostOrder(BT->lchild);
PostOrder(BT->rchild);
cout << BT->data << endl;
}
}
*/
//先序遍历非递归算法
/*
void PreOrderNoRecur(Btree root) {
stack<Btree> S;
while (root != NULL || !S.empty()) {
while (root != NULL) {
cout << root->data << endl;
S.push(root);
root = root->lchild;
}
if (!S.empty()) {
root = S.top();
S.pop();
root = root->rchild;
}
}
}
*/
//中序遍历非递归算法
/*
void InOrderNoRecur(Btree root) {
stack<Btree> S;
while (root != NULL || !S.empty()) {
while (root != NULL) {
S.push(root);
root = root->lchild;
}
if (!S.empty()) {
root = S.top();
cout << root->data << endl;
S.pop();
root = root->rchild;
}
}
}
*/
//后序遍历非递归算法
/*
void PostOrderNoRecur(Btree root) {
stack<List> newS;
while (root != NULL || !newS.empty()) {
while (root != NULL) {
List element;
element.ptr = root;
element.flag = 1;
newS.push(element);
root = root->lchild;
}
while (!newS.empty() && newS.top().flag == 2) {
cout << newS.top().ptr->data << endl;
newS.pop();
}
if (!newS.empty()) {
newS.top().flag = 2;
root = newS.top().ptr->rchild;
}
}
}
*/
//二叉树的层序遍历算法
void LevelOrder(Btree root) {
queue<Btree> Q;
Btree q;
if (root == NULL) {
return;
}
Q.push(root);
while (!Q.empty()) {
q = Q.front();
cout << q->data << endl;
Q.pop();
if (q->lchild != NULL) {
Q.push(q->lchild);
}
if (q->rchild != NULL) {
Q.push(q->rchild);
}
}
}
int main() {
//前序遍历创建树
Btree TreeOne = preCreateBT();
//先序遍历(递归)
//PreOrder(TreeOne);
//中序遍历(递归)
//InOrder(TreeOne);
//后序遍历(递归)
//PostOrder(TreeOne);
//先序遍历非递归算法
//PreOrderNoRecur(TreeOne);
//中序遍历非递归算法
//InOrderNoRecur(TreeOne);
//后序遍历非递归算法
//PostOrderNoRecur(TreeOne);
//利用队列实现层序遍历
LevelOrder(TreeOne);
}