问题 A: 复原二叉树

                                                   问题 A: 复原二叉树

                                                                          时间限制: 1 Sec  内存限制: 32 MB
                                                                                       提交: 310  解决: 188
                                                                        [提交][状态][讨论版][命题人:外部导入]

题目描述

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

输入

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

输出

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

样例输入

DBACEGF ABCDEFG
BCAD CBAD

样例输出

ACBFGED
CDAB

心得:此题是经典的二叉树遍历题目,给你先序遍历和中续遍历序列,让你求出后序遍历序列。此题给出的是字符串序列,因为可以把字符串当做字符数组来直接访问下标,所以此题就不涉及到转化的问题,减少了麻烦。又因为此题是多组测试用例,所以在每一组处理完毕后不要忘记了把字符串清空。 

accept code:

#include <iostream>
#include <string.h> 
using namespace std;

string pre,in;
struct node{
	char data;
	node* lchild;
	node* rchild;
};

node* create(int prel,int prer,int inl,int inr)
{
	if(prel>prer)
		return NULL;
	node* root=new node;
	root->data=pre[prel];
//	cout<<pre[prel]<<"**";
	int k;
	for(k=inl;k<=inr;k++)
	{
		if(in[k]==pre[prel])
			break;
	}
//	cout<<"k值"<<k<<endl;
	int numleft=k-inl;
//	cout<<"结点"<<numleft<<endl;
	root->lchild=create(prel+1,prel+numleft,inl,k-1);
	root->rchild=create(prel+numleft+1,prer,k+1,inr);
	return root;
} 

void postorder(node* root)
{
	if(root==NULL)
		return;
	postorder(root->lchild);
	postorder(root->rchild);
	printf("%c",root->data);
}

int main()
{
	while(cin>>pre>>in)
	{
		int len=pre.length();
//		cout<<len<<"&&"<<endl;
		node* root=create(0,len-1,0,len-1);	
		postorder(root);
		cout<<endl; 
		pre="";
		in="";	
	} 
	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_38938670/article/details/88674435