1030 求先序排列
板子,给中序后序,求先序序列
很简单,从后序找根,再从中序中找出根进行解决
尽管很绝对,但是后序的最后一个肯定是根
所以我们从后序中获得一个 根,输出,然后从中序中找到进行二分递归
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
char s[10];
char ss[10];
int len;
inline int find(char c)//从后序获得根,从中序找
{
for(int i=0;i<len;i++)
{
if(s[i]==c) return i;//找根的函数
}
}
void dfs(int tou,int wei,int tout,int weiw)
{
int m=find(ss[weiw]);//获取位置跟的位置
cout<<ss[weiw];
//输出这个根
/*原来这是个判断是否存在*/
//中序序列里面的根,肯定在头尾中间,这个判断条件很好想对吧
if(m>tou) dfs(tou,m-1,tout,weiw-wei+m-1);//wei-m为右子树结点数
if(m<wei) dfs(m+1,wei,tout+m-tou,weiw-1);//m-tou为左子树节点数
}
int main()
{
cin>>s;
cin>>ss;//输入
len=strlen(s);//获取长度
dfs(0,len-1,0,len-1);//然后搜索
return 0;
}