//二叉树的遍历
#include<bits/stdc++.h>
using namespace std;
typedef struct BiTNode{
char data;
struct BiTNode *rchild,*lchild;
}BiTNode,*BiTree;
bool CreatBiTree(BiTree &T)
{
char ch;
cin>>ch;
if(ch=='#')
T=NULL;
else
{
/*
T=new BiTNode;
if(!T)
exit(0);
*/
if(!(T=(BiTree)malloc(sizeof(BiTNode))))
exit(0);
T->data=ch;
CreatBiTree(T->lchild);
CreatBiTree(T->rchild);
}
return true;
}
//前序遍历
void PreOrderTraverse(BiTree T)
{
if(!T)
return;
cout<<T->data;
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
//中序遍历
void InOrderTraverse(BiTree T)
{
if(!T)
return;
InOrderTraverse(T->lchild);
cout<<T->data;
InOrderTraverse(T->rchild);
}
//后序遍历
void PostOrderTraverse(BiTree T)
{
if(!T)
return;
PostOrderTraverse(T->lchild);
PostOrderTraverse(T->rchild);
cout<<T->data;
}
//层序遍历
//队列,先将根节点入队,只要队列不空,就将左右子树入队,将队头输出 ,队头出队
void LevelOrderTraverse(BiTree T)
{
queue<BiTree> q;
q.push(T);
while(!q.empty())
{
if(q.front()->lchild!=NULL)
{
q.push(q.front()->lchild);
}
if(q.front()->rchild!=NULL)
{
q.push(q.front()->rchild);
}
cout<<q.front()->data;
q.pop();
}
}
int main()
{
BiTree T;
CreatBiTree(T);
cout<<"先序遍历:";
PreOrderTraverse(T);
cout<<endl;
cout<<"中序遍历:";
InOrderTraverse(T);
cout<<endl;
cout<<"后序遍历:";
PostOrderTraverse(T);
cout<<endl;
cout<<"层序遍历:";
LevelOrderTraverse(T);
return 0;
}
运行结果