版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30986521/article/details/82931738
设s1为树的后根遍历,s2为树的中根遍历,则s1[len - 1]为先根遍历的第一个节点,且s2中,s1[len - 1]左边的字符为s1[len - 1]的左子树,右边即是右子树。
例:中根:DBEAFC
后根:DEBFCA
此时A是树的根节点,根节点的左子树的中根遍历是BDE,右子树的中根遍历是FC,左子树的后根DEB,右子树的后根FC
子树也是树,递归。
#include <iostream>
#include <cstring>
using namespace std;
void f(char s1[], char s2[], int len)
{
if (len == 1)
{
cout << s1[len - 1];
}
else if (len > 1)
{
cout << s1[len - 1];
char* index = strchr(s2, s1[len - 1]);
int new_len = (int)(index - s2);
f(s1, s2, new_len);
f(s1 + new_len, index + 1, len - new_len - 1);
}
}
int main()
{
char s1[100], s2[100];
//s1后序, s2中序
cin >> s1 >> s2;
f(s1, s2, (int)strlen(s1));
return 0;
}