由先序遍历和中序遍历序列建立二叉树——

Description

按先序顺序和中序顺序输入二叉树的2个遍历序列,采用二叉链表建立该二叉树并用后序遍历顺序输出该二叉树的后序遍历序列。
Input

输入数据有多组,对于每组测试数据
第一行输入二叉树的先序序列,第二行为中序序列。
Output

对于每组测试数据输出该二叉树的后序序列
Sample Input

abdcef
dbaecf
Hint

dbefca

题意:

给你一个串的先序和中序遍历,要求输出后序遍历

题解:

判断一个位置的左右子树是这样的:
在样例中,首先我们得到了a,因为它是根,然后在中序遍历中找到a,那么db就是它的左子树,ecf是它的右子树,接下来是b,d是它的左子树,但是由于它的右边就是a了,那么它没有右子树,所以参数由(1,0,len-1,0,len-1)变成(2,1,2,0,1),以此类推。
所以我们在dfs的时候只需要传五个参数:(当前位置,先序遍历当前位置的左端点,先序遍历当前位置的右端点,中序遍历当前位置的左端点,中序遍历当前位置的右端点)

#include<bits/stdc++.h>
using namespace std;
char val[100005];
string s1,s2;
int num,len,pos1,pos2;
void dfs(int root,int l1,int r1,int l2,int r2)
{
	val[root]=s1[l1];
	if(l1==r1)
        return ;
    int ne=l2;
    while(s2[ne]!=s1[l1])
        ne++;
    if(ne!=l2)
        dfs(root<<1,l1+1,l1+ne-l2,l2,ne-1);
    if(ne!=r2)
        dfs(root<<1|1,l1+ne-l2+1,r1,ne+1,r2);
}
void dfs2(int root)
{
	if(val[root<<1])
		dfs2(root<<1);
	if(val[root<<1|1])
		dfs2(root<<1|1);
	printf("%c",val[root]);
}
int main()
{
	while(cin>>s1)
	{
	    memset(val,0,sizeof(val));
		cin>>s2;
		len=s1.length();
		num=1,pos2=pos1=0;
		dfs(1,0,len-1,0,len-1);
		dfs2(1);
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/tianyizhicheng/article/details/83829938