- 題目描述:
-
二叉樹的前序、中序、後序遍歷的定義:
前序遍歷:對任一子樹,先訪問跟,然後遍歷其左子樹,最後遍歷其右子樹;
中序遍歷:對任一子樹,先遍歷其左子樹,然後訪問根,最後遍歷其右子樹;
後序遍歷:對任一子樹,先遍歷其左子樹,然後遍歷其右子樹,最後訪問根。
給定一棵二叉樹的前序遍歷和中序遍歷,求其後序遍歷(提示:給定前序遍歷與中序遍歷能夠唯一確定後序遍歷)。
- 輸入:
-
兩個字符串,其長度n均小於等於26。
第一行爲前序遍歷,第二行爲中序遍歷。
二叉樹中的結點名稱以大寫字母表示:A,B,C....最多26個結點。
- 輸出:
-
輸入樣例可能有多組,對於每組測試樣例,
輸出一行,爲後序遍歷的字符串。
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
由二叉樹的前序遍歷序列與中序遍歷序列確定後序遍歷,這是由於二叉樹的前序遍歷序列與中序遍歷序列可以確定唯一的二叉樹,通常的做法是建樹,之後進行後序遍歷;但在這裏不用建樹,而是通過模擬後序遍歷得出二叉樹的後序遍歷序列。
#include<stdio.h>
#include<string.h>
char pre[27];
char in[27];
int pos[27];
int ind;
void postorder(char str[],int begin,int end)
{
int k=pos[ind];
if(begin==end)
{
ind++;
printf("%c",str[begin]);
}
else if(begin<end)
{
ind++;
postorder(str,begin,k-1);
postorder(str,k+1,end);
printf("%c",str[k]);
}
}
int main()
{
while(scanf("%s",pre)!=EOF)
{
scanf("%s",in);
int len=strlen(pre);
for(int i=0;i<len;i++)
for(int j=0;j<len;j++)
if(pre[i]==in[j])
pos[i]=j;
ind=0;
postorder(in,0,len-1);
printf("\n");
}
return 0;
}