您的位置:首页 > 理论基础 > 数据结构算法

数据结构上机测试4.1:二叉树的遍历与应用1

2014-02-18 19:47 405 查看


数据结构上机测试4.1:二叉树的遍历与应用1


Time Limit: 1000MS Memory limit: 65536K


题目描述

输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。


输入

第一行输入二叉树的先序遍历序列;

第二行输入二叉树的中序遍历序列。


输出

输出该二叉树的后序遍历序列。


示例输入

ABDCEF
BDAECF



示例输出

DBEFCA

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
struct node
{
char data;
struct node *l,*r;
};
struct node *creat(int len,char *str1,char *str2)
{
int k;
if(len<=0)
return NULL;
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
head->data = *str1;
char *p;
for(p = str2;p!=NULL;p++)
if(*p==*str1)
break;
k = p-str2;
head->l = creat(k,str1+1,str2);
head->r = creat(len-k-1,str1+k+1,p+1);
return head;
}
void houxu(struct node *p)
{
if (p)
{

houxu(p->l);
houxu(p->r);
printf("%c",p->data);

}
}
int main()
{
int len;
char str1[100],str2[100];
struct node *head;
head = (struct node *)malloc(sizeof(struct node ));
scanf("%s %s",str1,str2);
len = strlen(str1);
head = creat(len,str1,str2);
houxu(head);
printf("\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: