数据结构上机测试4.1:二叉树的遍历与应用1
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
Input
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
Output
输出该二叉树的后序遍历序列。
Sample Input
ABDCEF BDAECF
Sample Output
DBEFCA
Hint
Source
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char pre[55];
char mid[55];
struct node
{
char data;
struct node *left;
struct node *right;
};
struct node *creat(char *pre, char *mid, int n)
{
if(n <= 0) return NULL;
struct node *root;
root = (struct node *)malloc(sizeof(struct node));
root -> data = *pre;
int k;
for(k = 0; k < n; k++)
{
if(mid[k] == pre[0])
break;
}
root -> left = creat(pre + 1, mid, k);
root -> right = creat(pre + k + 1, mid + k + 1, n - k - 1);
return root;
};
void post(struct node *root)
{
if(root)
{
post(root -> left);
post(root -> right);
printf("%c", root -> data);
}
}
int main()
{
int n;
scanf("%s", pre);
scanf("%s", mid);
struct node *root;
n = strlen(mid);
root = creat(pre, mid, n);
post(root);
printf("\n");
return 0;
}