D

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=83498#problem/D

题意:

      多组案例,每组案例给定二叉树的先序遍历和中序遍历,输出后序遍历(每组案例不超过26个字符)

      案例:

           Sample Input

           DBACEGF ABCDEFG
           BCAD CBAD

           Sample Ouput

           ACBFGED
           CDAB

分析:

      先序遍历的第一个字符就是根,因此在中序遍历中找到它,即可知左右子树的先序遍历和中序遍历。

      先执行递归遍历构造二叉树,再找出后序遍历即可。

源代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 char preorder[30];//前序
 4 char inorder[30];//中序
 5 char postorder[30];//后序
 6 void build(int n, int pre, int in, int rec)
 7 {
 8     if(n <= 0) return ;//无子树 
 9     int i;
10     for(i = 0; ; i++)
11     {
12         if(preorder[pre] == inorder[in+i])//找到根位置 
13         break;
14     }
15     postorder[n-1+rec] = preorder[pre];//记录
16     build(i, pre+1, in, rec);//左子树
17     build(n-i-1, pre+i+1, in+i+1, rec+i);//右子树 
18 }
19 int main()
20 {
21     int n;
22     while(scanf("%s%s", preorder, inorder) != EOF)//输入前序,中序
23     {
24         n = strlen(preorder);//序长
25         build(n, 0, 0, 0);//建立树
26         postorder[n] = ''; 
27         printf("%s
",postorder);
28     }
29     return 0;
30 } 
原文地址:https://www.cnblogs.com/huaszjh/p/4671528.html