复原二叉树

拥有回忆 提交于 2020-01-30 00:17:55

题目描述

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

输入

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

输出

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

样例输入

DBACEGF ABCDEFG
BCAD CBAD

样例输出

ACBFGED
CDAB

代码

#include<bits/stdc++.h>
using namespace std;
struct node
{
	char data;
	node *lchild;
	node *rchild;
};
node *creat(string a,string b)
{
	string pre1,pre2,in1,in2;
	node *root=NULL;
	if(a.size()>0)
	{
		root=new node;//申请内存 
		root->data=a[0];
		int index=b.find(a[0]);
		pre1=a.substr(1,index);
		pre2=a.substr(index+1,a.size()-1-index);
		in1=b.substr(0,index);
		in2=b.substr(index+1,b.size()-1-index);
		root->lchild=creat(pre1,in1);
		root->rchild=creat(pre2,in2);
	}
	return root;
}
void postorder(node *root)
{
	if(root==NULL)
		return;
	postorder(root->lchild);
	postorder(root->rchild);
	printf("%c",root->data);
}
int main()
{
	string a,b;
	while(cin>>a>>b)
	{
		node *t=creat(a,b);
		postorder(t);
		printf("\n"); 
	}
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!