由中序序列和后序序列唯一确定一棵二叉树

本文介绍了一种根据给定的中序和后序遍历序列构建二叉树的方法,并提供了详细的C++实现代码。通过递归地寻找根节点并划分左右子树,最终能够重建出原始的二叉树结构。
 

已知一棵二叉树的中序和后序序列如下:

中序:GL D H B E I A C J F K

后序:LG H D I E B J K F C A

则可以唯一确定一棵二叉树。

#include<iostream.h>

#include<string.h>

#include<stdlib.h>

#define MAX 20 /*预定义字符数组的最大长度*/

typedef struct tnode /*该结构体类型为树结点的类型*/

{

char data;

struct tnode *lchild;

struct tnode *rchild;

} *bt;

void in_post_to_bt(char *in,char *post,int len,bt &T) /*由长度为len的中序序列in和后序序列post唯一确定一棵二叉树T*/

{

int k;

if(len<=0)

{

T=NULL;

return;

}

for(char *temp=in;temp<in+len;temp++) /*在中序序列in中找到根节点所在的位置*/

if(*(post+len-1)==*temp)

{

k=temp-in;/*k为根结点在中序序列中的下标*/

T=(bt)malloc(sizeof(struct tnode));

T->data =*temp;

break;

}

in_post_to_bt(in,post,k,T->lchild ); /*建立左子树*/

in_post_to_bt(in+k+1,post+k,len-k-1,T->rchild ); /*建立右子树*/

}

void in_visit(bt T)/*中序遍历树T*/

{

if(T)

{

in_visit(T->lchild );

cout<<T->data ;

in_visit(T->rchild );

}

}

void post_visit(bt T)/*后序遍历树*/

{

if(T)

{

post_visit(T->lchild );

post_visit(T->rchild );

cout<<T->data ;

}

}

main()

{

char in[MAX+1],post[MAX+1];

cout<<"输入中序序列:";

cin>>in;

cout<<"输入后序序列:";

cin>>post;

bt T;

int len_in=strlen(in),len_post=strlen(post);

if(len_in<=MAX&&len_post<=MAX)

in_post_to_bt(in,post,len_in,T);

cout<<endl<<"输出中序序列:";

in_visit(T);

cout<<endl<<"输出后序序列:";

post_visit(T);

cout<<endl;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值