[2001年NOIP普及组] 求先序排列
[2001年NOIP普及组] 求先序排列
思路:递归分治,找到根节点之后把左右子树分开再递归。写一个递归函数,参数为树分别在序列中的下标位置midL,midR,lterL,lterR,在中序中和在后序中。
直接拜访后序最后一个下标根节点的位置,在中序中找到这个根节点pRoot的位置,再分成左右子树,分别递归,输出根节点。
代码如下:
#include<iostream>
#include<cstring>
using namespace std;
int ml,ll;
char mid[9],lter[9];//中序遍历和后序遍历
void fmal(int midL,int midR,int lterL,int lterR)
{
if(midL==midR)//二者相等
{
cout<<mid[midL];//直接打印
return ;//返回
}
//读取根节点
char root=lter[lterR];
//寻找根节点
int pRoot;
for(pRoot=0;pRoot<=midR;pRoot++)
if(mid[pRoot]==root)
break;
//打印根节点
cout<<root;
//递归
if(pRoot!=midL)//左子树不空
fmal(midL,pRoot-1,lterL,lterL+pRoot-midL-1);
if(pRoot!=midR)
fmal(pRoot+1,midR,lterR-(midR-pRoot),lterR-1);
return ;
}
int main()
{
cin>>mid;
cin>>lter;
ml=strlen(mid);
ll=strlen(lter);
fmal(0,ml-1,0,ll-1);
return 0;
}