数据结构上机测试4.1:二叉树的遍历与应用1
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
Input
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
Output
输出该二叉树的后序遍历序列。
Sample Input
ABDCEF BDAECF
Sample Output
DBEFCA
Hint
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char pre[1001], mid[1001];
int len;
struct node
{
char data;
struct node *l, *r;
};
struct node *creat(int m, char *pre, char *mid)
{
if(!m)
{
return NULL;
}
int i;
struct node *root;
root = (struct node *)malloc(sizeof(struct node));
root-> data = pre[0];
for(i = 0; i < m; i++)
{
if(pre[0] == mid[i])
{
break;
}
}
root-> l = creat(i, pre + 1, mid);
root-> r = creat(m - i - 1, pre + 1 + i, mid + 1 + i);
return root;
}
void hou(struct node *root)
{
if (root != NULL)
{
hou(root ->l);
hou(root ->r);
printf("%c" , root ->data);
}
}
int main()
{
struct node *root;
scanf("%s" , pre);
scanf("%s" , mid);
len = strlen(pre);
root = creat(len, pre, mid);
hou(root);
return 0;
}
/***************************************************
User name: jk170717
Result: Accepted
Take time: 0ms
Take Memory: 152KB
Submit time: 2018-08-08 11:28:54
****************************************************/