数据结构上机测试4.1:二叉树的遍历与应用1
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
Input
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
Output
输出该二叉树的后序遍历序列。
Sample Input
ABDCEF BDAECF
Sample Output
DBEFCA
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct node
{
char x;
node *l, *r;
};
node *create(char *pre, char *ord, int len)
{
node* rt = new node();
for(int i = 0; i < len; i++)
{
if(pre[0] == ord[i])
{
rt->x = pre[0];
rt->l = create(pre+1, ord,i);
rt->r = create(pre+i+1, ord+i+1, len - i -1);
return rt;
}
}
return NULL;
}
void la(node *rt)
{
if(rt)
{
la(rt->l);
la(rt->r);
printf("%c", rt->x);
}
}
int main()
{
char pre[110],ord[110];
scanf("%s%s",pre,ord);
node *root;
root = create(pre,ord,strlen(pre));
la(root);
return 0;
}