给定二叉树的后序遍历和中序遍历,求其前序遍历(后中定序)

题目描述

二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的后序遍历中序遍历,求其前序遍历(提示:给定后序遍历与中序遍历能够唯一确定前序遍历)。

输入

两个字符串,其长度n均小于等于26。
第一行为后序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。

输出

输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。

样例输入

DCBGFEA
DCBAEFG
CBA
CBA

样例输出

ABCDEFG
ABC

思路分析

先根据后序遍历和中序遍历构造一棵二叉树,然后再对其先序遍历。
构造的原理是用的后序遍历序列的最后一个是根,在中序遍历中分割根的左子树和右子树的中序遍历序列,

并且后序遍历序列的除掉根外的前半部分是根的左子树的后序遍历,后半部分是右子树的后序遍历。
如图,就可以递归地构造二叉树了

AC代码:

//后中定序。输出先序遍历序列 
#include <iostream>
#include <cstdio>
using namespace std;

struct node{
	char data;
	node* lchild;
	node* rchild;
};
void PreOrder(node* root){//先序遍历 
	if(root==NULL){
		return;
	}
	printf("%c",root->data);
	PreOrder(root->lchild);
	PreOrder(root->rchild);
}
node* Create(string postorder,string inorder){
	node* root=NULL;
	if(postorder.size()>0){
		root=new node;
		int len=postorder.size();
		root->data=postorder[len-1];
		root->lchild=NULL;
		root->rchild=NULL;
		string post1,post2;
		string in1,in2;
		int index=inorder.find(postorder[len-1]);
		in1=inorder.substr(0,index);
		in2=inorder.substr(index+1,inorder.size()-index-1);
		post1=postorder.substr(0,index);
		post2=postorder.substr(index,postorder.size()-index-1);
		
		root->lchild=Create(post1,in1);
		root->rchild=Create(post2,in2);
	}
	return root;
}
int main(int argc, char** argv) {
	string s1,s2;
	while(cin>>s1>>s2){
		node* root=Create(s1,s2);
		PreOrder(root);
		cout<<endl;
	} 
	return 0;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值