POJ 2255

ACM:已知二叉树的前序,中序,求后序

思路:

由前序得出根节点,在中序中,根节点左边为左子树,根节点右边为右子树,递归遍历

#include <iostream>
using namespace std;

typedef struct _BTNode
{
	char data;
	_BTNode *lchild,*rchild;	
} BTNode;

char *Predata,*Indata;

void build(int preLeft,int preRight,int inLeft,int inRight)//四个参数分别为前序、中序的起点和终点 
{
	int root;
	
	for(root=inLeft;root<=inRight;root++)	
	{
		if(Predata[preLeft]==Indata[root])	//找到根节点 
			break;
	}
	
	int LeftSize=root-inLeft;//计算左子树的规模和右子树规模 
	int RightSize=inRight-root;
	
	if(LeftSize>0)//递归左子树 
	{
		build(preLeft+1,preLeft+LeftSize,inLeft,root-1);
	}
	if(RightSize>0)//递归右子树 
	{
		build(preLeft+LeftSize+1,preRight,root+1,inRight);
	}
	cout<<Indata[root]<<" ";//输出根 
}

int main(int argc, char *argv[])
{
	Predata="DBACEGF";//前序 
	Indata="ABCDEFG";//中序 
	
	build(0,strlen(Predata)-1,0,strlen(Indata)-1);
	cout<<endl;
	
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值