数据结构上机测试4.1:二叉树的遍历与应用1
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
Input
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
Output
输出该二叉树的后序遍历序列。
Sample Input
ABDCEF
BDAECF
Sample Output
DBEFCA
把这两个字符串的左右分别定义为l1,r1,l2,r2,然后进行操作,那两个找子根的方法可以自己在纸上推演一下
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
char a[60];
char b[60];
int len;
void find_postorder_tree(int l1,int r1,int l2,int r2);
int main()
{
scanf("%s%s",a,b);
len=strlen(a);
find_postorder_tree(0,len-1,0,len-1);
printf("\n");
return 0;
}
void find_postorder_tree(int l1,int r1,int l2,int r2)
{
if(r1<l1||r2<l2)//结束标志是左大于右
{
return;
}
int pos=l2;
while(a[l1]!=b[pos])
{
pos++;//在中序中找到根的位置
}
find_postorder_tree(l1+1,l1+(pos-l2),l2,pos-1);//找左子根
find_postorder_tree(l1+(pos-l2)+1,r1,pos+1,r2);//找右子根
printf("%c",b[pos]);
}