|
|
#2
小依2010-06-14 11:42
|
根据中序遍历和层次遍历建立树,我用的是递归思路,可是.......哎总找不到那错了.
#include <stdio.h>
#include <malloc.h>
#define maxsize 100
typedef char ElemType;
typedef struct node
{
ElemType data;
struct node *lchild,*rchild;
}BiNode,*BiTree;
typedef struct order
{
ElemType data[maxsize];
int nodes;
}order;
order Creat_order()
{
order a;
ElemType x;
a.nodes=0;
scanf("%c",&x);
while(x!='#')
{
a.data[++a.nodes]=x;
scanf("%c",&x);
}
return a;
}
BiTree CreatBiTree(order inorder,order leorder,int f1,int l1,int f2)
{
int root;
BiTree T;
for(root=f1;inorder.data[root]!=leorder.data[f2];root++);
T=(BiTree)malloc(sizeof(BiNode));
T->data=inorder.data[root];
if(f1==root)
{
T->lchild=NULL;
if(l1==root) T->rchild=NULL;
else T->rchild=CreatBiTree(inorder,leorder,root+1,l1,f2+1);
}
else
{
T->lchild=CreatBiTree(inorder,leorder,f1,root-1,f2+1);
if(l1==root) T->rchild=NULL;
else T->rchild=CreatBiTree(inorder,leorder,root+1,l1,f2+2);
}
return T;
}
int main()
{
BiTree T;
int f1,l1,f2;
order inorder,leorder;
printf("Input the inorder:");
inorder=Creat_order();
printf("Input the leorder:");
leorder=Creat_order();
f1=f2=1;
l1=inorder.nodes;
T=CreatBiTree(inorder,leorder,f1,l1,f2);
return 0;
}