假设一棵二叉树的先序遍历为DBACEGF,中序遍历为ABCDEFG,输出它的后序遍历序列。
先序遍历的第一个字符就是根,从中序遍历中找到它,就分开了左右子树,如此可递归下去
#include <iostream>
#include <cstring>
using namespace std;
int build(int n, char * s1, char * s2, char * s)
{
if (n <= 0)
{
return 0;
}
int p = strchr(s2, s1[0]) - s2;
build(p, s1 + 1, s2, s);
build(n - p - 1, s1 + p + 1, s2 + p + 1, s + p);
s[n - 1] = s1[0];
}
int main()
{
char s1[20] = {'D', 'B', 'A', 'C', 'E', 'G', 'F'};
char s2[20] = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
char s3[20] = {0};
build(7, s1, s2, s3);
for (int i = 0; i < 7; ++i)
{
cout << s3[i] << endl;
}
return 0;
}