今天主要是学了二叉树知道包括中序在内的两个求另外一个,这里是知道中序和后续求前序。
当然,这道题完全可以不用创建树,但是为了练练把我就创建了个树。
虽然道路有些曲折,但庆幸自己没放弃,相信最后的结果将是掷地有声的、众人艳羡的成功之果。
问题 B: 二叉树,知中序后序,求先序(递归)
描述
已知二叉树的中序、后序,建树求先序。
格式
输入格式
中序序列
后序序列
输出格式
先序序列
样例
样例输入 Copy
d g b a e c f
g d b e f c a
样例输出 Copy
a b d g c e f
下面我用建树和不建树两种方法:
1.建树做法
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Node
{
struct Node* left;
struct Node* right;
char val;
} Node;
Node *build(char midsort[],char lastsort[],int len)
{
int i,r;
char ch;
if(len==0)//如果没有数据了就返回个空
return NULL;
ch=lastsort[len-1];//因为是后序,所以找到根节点
r=-1;
for(i=0; i<len; i++)//找到根节点,在中序中找到根节点的位置
{
if(ch==midsort[i])
{
r=i;
break;
}
}
Node *root=(Node*)malloc(sizeof(Node));//创建节点
root->val=ch;//将数据放入根节点中
root->left=build(midsort,lastsort,r);//创建左子树
root->right=build(midsort+r+1,lastsort+r,len-r-1);//创建右子树
return root;//返回根节点
}
void printtree(Node* t)
{
if(t==NULL)
return;
printf("%c ",t->val);
printtree(t->left);
printtree(t->right);
}
int main()
{
Node *t;
char midsort[1001]={0},lastsort[1001]={0};
int i,j;
int len;
char m;
i=j=0;
while(~scanf("%c%c",&midsort[i++],&m))//首先是多组输入,谨慎点吧
{
if(m=='\n')
break;
}
while(~scanf("%c%c",&lastsort[j++],&m))
{
if(m=='\n')
break;
}
len=strlen(midsort);//判断长度
t=build(midsort,lastsort,len);//创建树,返回根
printtree(t);
}
2.不建树做法:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void build(char midsort[],char lastsort[],int len)
{
int i,r;
char ch;
if(len<=0)//当前数据是0表示当前节点为空;
return ;
ch=lastsort[len-1];//根据后序找到根节点
for(i=0; i<len; i++)
{
if(ch==midsort[i])
{
r=i;
break;
}
}
printf("%c ",ch);//不建树可以直接输出
build(midsort,lastsort,r);//在左子树中找
build(midsort+r+1,lastsort+r,len-r-1);//右子树中找
}
int main()
{
char midsort[101]={0},lastsort[101]={0},m;
int i,j,len;
i=j=0;
while(~scanf("%s%c",&midsort[i++],&m))
{
if(m=='\n')
break;
}
while(~scanf("%s%c",&lastsort[j++],&m))
{
if(m=='\n')
break;
}
len=strlen(midsort);
build(midsort,lastsort,len);
}