您的位置:首页 > 编程语言 > C语言/C++

已知前序、中序,递归建立二叉树(C语言)

2017-05-27 17:21 267 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐