最近要弄论文实在弄的头疼,没时间学习C++,趁下午没事就实现了二叉书的遍历,二叉树怎么说也是相当重要的东西,三种遍历顺序都应该熟悉掌握。
我的二叉树的先序为:ABDCEFG (先序访问根节点,再先序访问左子树,再先序访问右子树) 中序为:DBAECGF(中序访问左子树,再中序访问根节点,再中序访问右子树) 后序为:DBEGFCA(中序遍历左子树,再中序遍历右子树,再访问根节点)下面是实现代码:
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
class Btree
{
public:
string data;
Btree*pLchid;
Btree*pRchid;
};
Btree*creat()
{
Btree*pA=new Btree;
Btree*pB=new Btree;
Btree*pC=new Btree;
Btree*pD=new Btree;
Btree*pE=new Btree;
Btree*pF=new Btree;
Btree*pG=new Btree;
pA->data='A';
pB->data='B';
pC->data='C';
pD->data='D';
pE->data='E';
pF->data='F';
pG->data='G';
pA->pLchid=pB;
pA->pRchid=pC;
pB->pLchid=pD;
pB->pRchid=NULL;
pD->pLchid=NULL;
pD->pRchid=NULL;
pC->pRchid=pF;
pC->pLchid=pE;
pE->pLchid=NULL;
pE->pRchid=NULL;
pF->pLchid=pG;
pF->pRchid=NULL;
pG->pRchid=NULL;
pG->pLchid=NULL;
return pA;
}
void preBtree(Btree*p)
{
if(NULL!=p)
{
cout<<p->data<<endl;
if(NULL!=p->pLchid)
{
preBtree(p->pLchid);
}
if(NULL!=p->pRchid)
{
preBtree(p->pRchid);
}
}
}
void postBtree(Btree*p)
{
if(NULL!=p)
{
if(NULL!=p->pLchid)
{
postBtree(p->pLchid);
}
if(NULL!=p->pRchid)
{
postBtree(p->pRchid);
}
cout<<p->data<<endl;
}
}
void inBtree(Btree*p)
{
if(NULL!=p)
{
if(NULL!=p->pLchid)
{
inBtree(p->pLchid);
}
cout<<p->data<<endl;
if(NULL!=p->pRchid)
{
inBtree(p->pRchid);
}
}
}
int main()
{
Btree*p=creat();
cout<<"先序遍历:"<<endl;
preBtree(p);
cout<<endl;
cout<<"中序遍历:"<<endl;
inBtree(p);
cout<<endl;
cout<<"后序遍历:"<<endl;
postBtree(p);
cout<<endl;
system("pause");
return 0;
}