转载自(2条消息) 数据结构上机测试4.1:二叉树的遍历与应用1_Dmenghu的博客-CSDN博客
Description
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
Input
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
Output
输出该二叉树的后序遍历序列。
Sample
Input
ABDCEF BDAECF
Output
DBEFCA
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str1[100],str2[100];
int len;
struct node{
struct node *lchild,*rchild;
int date;
};
struct node *create(int len,char *str1,char *str2)
{
int i;
struct node *root;
if(len==0)
return NULL;
root=(struct node*)malloc(sizeof(struct node));
root->date=str1[0];
for(i=0;i<len;i++)
{
if(str2[i]==root->date)
break;
}
root->lchild=create(i,str1+1,str2);//左子树,确定了str2第i个输入等于根节点后,左边的都是左子树上的点。因为中序是左-根-右。所以,第i-1之前的结点都是左子树上的点。长度为i,str1+1的意思是从str1之后的那个点开始,因为str1第一个点是根节点,所以,左子树的根,要从下一个点开始。当i一直减少等于0的时候,就返回NULL。
root->rchild=create(len-i-1,str1+i+1,str2+i+1);//右子树,因为找到了根节点的位置,是i,所以,右子树的长度为i+1到len-(i+1),简单整理一下就是len-i-1,右子树的左子树从str1+i+1开始,右子树的右子树从str2+i+1开始。简单解释一下,以右子树的左子树为例,str1+i,这个代表了根节点的位置,根节点的下一个就是右子树的开始,所以str1+i+1。右子树的右子树同理。
//这是我的理解,有不对的地方还请指出。
return root;
};
void hou(struct node *root)
{
if(root)
{
hou(root->lchild);
hou(root->rchild);
printf("%c",root->date);
}
}
int main()
{
scanf("%s",str1);
scanf("%s",str2);
struct node* root;
len=strlen(str1);
root=create(len,str1,str2);
hou(root);
}