其他分享
首页 > 其他分享> > 1096 问题 A: 复原二叉树

1096 问题 A: 复原二叉树

作者:互联网

题目描述

小明在做数据结构的作业,其中一题是给你一棵二叉树的前序遍历和中序遍历结果,要求你写出这棵二叉树的后序遍历结果。

输入

输入包含多组测试数据。每组输入包含两个字符串,分别表示二叉树的前序遍历和中序遍历结果。每个字符串由不重复的大写字母组成。

输出

对于每组输入,输出对应的二叉树的后续遍历结果。

样例输入

DBACEGF ABCDEFG
BCAD CBAD

样例输出

ACBFGED
CDAB
//问题 A: 复原二叉树
#include<cstdio>
#include<cstring>
const int maxn=30;
//#define elemtype char
struct node
{
//	elemtype date;
	char date;
	node* lchild;
	node* rchild;
};
char pre[maxn],in[maxn],post[maxn];//先序、中序、后序序列

//Step 1:根据先序遍历和中序遍历序列,重建二叉树
//当前先序序列区间为[preL,preR]中序序列区间为[inL,inR],返回根节点
node* create(int preL,int preR,int inL,int inR)
{
	if(preL>preR)
	{
		return NULL;//先序序列长度小于0,直接返回
	}
	node *root=new node;//新建根节点
	root->date=pre[preL];//先序序列第一个顶点为根节点
	int k;
	for(k=inL;k<=inR;k++)
	{
		if(in[k]==pre[preL])//中序序列中找到该根节点
		{
			break;
		}
	}
	int num_left=k-inL;//左子树节点个数

	//左子树先序序列区间为[preL+1,preL+num_left]中序序列区间为[inL,k-1]
	root->lchild=create(preL+1,preL+num_left,inL,k-1);
	//右子树先序序列区间为[preL+num_left+1,preR]中序序列区间为[k+1,inR]
	root->rchild=create(preL+num_left+1,preR,k+1,inR);
	return root;
}
//Step 2:后序遍历
void postorder(node *root)
{
	if(root==NULL)
	{
		return ;
	}
	postorder(root->lchild);
	postorder(root->rchild);
	printf("%c",root->date);
}
int main()
{
	while(gets(pre)!=NULL)
	{	
		gets(in);
		int n;//结点个数
		n=strlen(pre);
		node* root=create(0,n-1,0,n-1);
		postorder(root);
		printf("\n");
	}
	return 0;
}

 

标签:node,preL,1096,遍历,int,二叉树,复原,root
来源: https://blog.csdn.net/sinat_33269610/article/details/88668121