#include <stdio.h>
#include <malloc.h>
int pre[]={1,2,4,5,3,6,7};//前序序列
int ino[]={4,2,5,1,6,3,7};//中序序列
struct BTree
{
struct BTree *left,*right;
int data;
};//树节点定义
void BuildBTree(struct BTree **T,int preL,int preR,int inoL,int inoR)//递归建树
{
if(preL>preR) return;
int e=pre[preL];
int root=inoL;
while(ino[root]!=e&&root<=inoR) ++root;
(*T)=(struct BTree *)malloc(sizeof(struct BTree));
(*T)->left=NULL;
(*T)->right=NULL;
(*T)->data=e;
BuildBTree(&(*T)->left,preL+1,preL+root-inoL,inoL,root-1);
BuildBTree(&(*T)->right,preL+root-inoL+1,preR,root+1,inoR);
}
void Treverse(struct BTree *T)//中序遍历
{
if(T)
{
Treverse(T->left);
printf("%d ",T->data);
Treverse(T->right);
}
}
int main()
{
struct BTree *T=NULL;
BuildBTree(&T,0,6,0,6);
Treverse(T);
return 0;
}
已知前序、中序,递归建立二叉树(C语言)
最新推荐文章于 2024-05-29 23:34:43 发布