A common problem in data structures is to determine the traversal of a binary tree.(前序遍历,中序遍历推导后序遍历)

题目:

A common problem in data structures is to determine the traversal of a binary tree.(前序遍历,中序遍历推导后序遍历)

题目大意:

输入一个t表示测试样例个数
每个测试样例由一个数表示节点数,后面是前序遍历和中序遍历经过的节点值的顺序
输出后序遍历经过的节点值的顺序

代码:

#include<iostream>
#include<cstdio>
#include<stdlib.h>
using namespace std;
char a[105],b[105];
struct tree
{
    tree *ltree;
    tree *rtree;
    char date;
};
tree* buildtree(char *left,char *right,int sizee)//left:前序遍历顺序。right:中序遍历顺序
{
    tree *t;
    for(int i=0; i<sizee; i++)
    {
        if(left[0]==right[i])
        {
            t=(tree *)malloc(sizeof(tree));
            t->date=right[i];
            t->ltree=buildtree(left+1,right,i);
            t->rtree=buildtree(left+i+1,right+i+1,sizee-i-1);
            return t;
        }
    }
    return NULL;
}
void posttree(tree *t)//后序遍历输出函数
{
    if(t)
    {
        posttree(t->ltree);
        posttree(t->rtree);
        cout<<t->date;
    }
}
int main()
{
    int t;
    scanf("%d",&t);//输入t循环t次
    while(t--)
    {
        int n;
        int sizee;
        scanf("%d",&n);//输入n代表有n个节点
        scanf("%s %s",a,b);//输入前序遍历和后序遍历经过的各节点值
        tree *root;//定义根节点
        root=buildtree(a,b,n);//建树
        posttree(root);//后序遍历输出
        putchar('\n');
    }
    return 0;
}