UVa 536

题意

给出一颗二叉树的前序遍历和中序遍历, 输出后序遍历

思路

无需建树, 递归操作即可

记录

前序遍历(先根遍历) : 如果二叉树为空则进行空操作, 否则首先访问根节点, 然后前序遍历左子树, 最后前序遍历右子树

中序遍历(中根遍历) : 如果二叉树为空则进行空操作, 否则首先中序遍历左子树, 然后访问根节点, 最后中序遍历右子树

后序遍历(后根遍历) : 如果二叉树为空则进行空操作, 否则首先后序遍历左子树, 然后后序遍历右子树, 最后访问根节点

AC代码

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int maxn = 50;
char s1[maxn], s2[maxn], s3[maxn]; //分别是前序, 中序, 后序
int root;

void Tree_Recovery( char *s1, char *s2, int len ){
    s3[++root] = *s1;
    char *p = s2;
    while( *p != *s1 )  p++;

p++;
    int temp = p - s2; 
    if( temp < len ) 
        Tree_Recovery(s1+temp, p, len-temp);
    if( temp > 1 )
        Tree_Recovery(s1+1, s2, temp-1);
    return ;
}

int main()
{
    int len;
    while( ~scanf("%s%s",s1,s2) )
    {
        len = strlen(s1);
        root = 0;
        Tree_Recovery( s1, s2, len );
        while( root )   putchar( s3[root--] );  //倒序输出s3内元素
        cout << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/JinxiSui/p/9740610.html