二叉树的三种遍历

最近要弄论文实在弄的头疼,没时间学习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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值