二叉树广度优先遍历
二叉树的广度优先遍历是指对一个二叉树从根结点开始,从顶层到底层,从左向右依次遍历二叉树。
在进行广度优先遍历时,先被访问的结点的左结点和右结点也先被访问,因此需要使用队列来进行访问。
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
typedef char datatype;
typedef struct Node
{
datatype data;
struct Node *lchild;
struct Node *rchild;
}*BiTree, Node;
void CreateBiTree(BiTree *T)
{
/*这里的T是(BiTree *)类型的指针,故(*T)是BiTree类型的指针,lchild,rchild都是BiTree类型变量*/
/*BiTree *T 就相当于Node** T。*/
datatype ch;
cin>>ch;
if(ch=='#')
*T = NULL;
else
{
*T = (BiTree)malloc(sizeof(Node));
if(!*T)
exit(OVERFLOW);
else
{
(*T)->data = ch;
/*这里先对T解引用,然后指向自己的左结点,探后对自己的左结点取指针,传入CreateBiTree*/
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
}
void breadthFirstSearch(BiTree T)
{
queue<BiTree> nodeQueue;
nodeQueue.push(T);
Node *node;
while (!nodeQueue.empty())
{
node = nodeQueue.front();
nodeQueue.pop();
cout<<node->data<<"\t";
if (node->lchild)
{
nodeQueue.push(node->lchild);
}
if (node->rchild)
{
nodeQueue.push(node->rchild);
}
}
}
int main()
{
int level = 1;
BiTree bitree = NULL;
CreateBiTree(&bitree);
cout << "广度优先遍历" << endl;
breadthFirstSearch(bitree);
}