首先我们先了解一下什么是层序遍历:
层序遍历:进行层序遍历时,对某一层的节点访问完后,再按照他们的访问次序对各个节点的左孩子和右孩子顺序访问,这样一层一层进行,先访问的节点其左右孩子也要先访问,这正好符合队列的操作特性。
二叉树的层序遍历算法:
#include <iostream>
#include <stdlib.h>
using namespace std;
/*树的节点*/
struct node
{
node *lchild, *rchild; //左右孩子指针
int value; //树节点数据
};
/*链队节点*/
struct Node
{
Node *next;
node *value;//树的节点地址
};
/*链队的类*/
class Queue
{
public:
Queue();
void EnQueue(node *T); //入队
void Display(); //打印
node *Front(); //返回上一个元素
bool Empty();
private:
Node *head;//队头指针
Node *rear;//尾指针
};
/*判断链队是否为满*/
bool Queue::Empty()
{
if (head == NULL)
return false;
else
return true;
}
/*出队函数:队头指针向后移,返回先前的队头指针*/
node *Queue::Front()
{
node *temp = head->value;
head = head->next;
return temp;
}
/*打印函数*/
void Queue::Display()
{
if (head == NULL)
return;
Node *p = head;
while (p)
{
cout << p->value << ' ';
p = p->next;
}
}
/*队列初始化*/
Queue::Queue()
{
head = rear = NULL;
}
/*入队函数*/
void Queue::EnQueue(node *T)
{
if (head == NULL)
{
head = new Node;
head->value = T;
head->next = NULL;
rear = head;
}
else
{
Node *p = new Node;
p->next = NULL;
p->value = T;
rear->next = p;
rear = p;
}
}
/*二叉树的类*/
class BITree
{
public:
node* CreateTree(node *T);
void LeverOrder(node *T);
private:
Queue Q;
};
/*层序遍历*/
void BITree::LeverOrder(node *T)
{
node *p = T;
Q.EnQueue(p);
while (Q.Empty())
{
p = Q.Front();
cout << p->value << ' ';
if (p->lchild)
Q.EnQueue(p->lchild);
if (p->rchild)
Q.EnQueue(p->rchild);
}
}
/*建立二叉树*/
node* BITree::CreateTree(node *T)
{
int i;
cin >> i;
if (i == 0)
T = NULL;
else
{
T = new node;
T->value = i;
T->lchild = CreateTree(T->lchild); //递归建立左子树
T->rchild = CreateTree(T->rchild);//递归建立右子树
}
return T; //返回根指针
}
int main()
{
cout << "请输入你要输入的字符,按0结束:" << endl;
node *T = NULL;
BITree text; //定义一个二叉树
T = text.CreateTree(T); //建立二叉树
text.LeverOrder(T); //层序遍历
getchar();
getchar();
return 0;
}
// 1 2 3 4 0 0 5 0 0 0 6 7 0 0 8 0 0