这次是用插入法创建二叉搜索树
#include<stdio.h>
#include<stdlib.h>
int flag;
typedef int elemtype;
typedef struct B
{
elemtype data;
struct B *lchild,*rchild;
}BiTNode,*BiTree;
void Init_BST(BiTree *BST)
{
*BST=NULL;
}
int Search_BST(BiTree *BST,BiTree *p,BiTree *q,elemtype key)
{
//int flag=0;
if(*BST==NULL)
{
return 0;
}
else if((*BST)->data ==key)
{
*q=*BST;
return 1;
}
else if(key>(*BST)->data)
{
*p=*BST;
Search_BST(&(*BST)->rchild,p,q,key);
}
else if(key<(*BST)->data)
{
*p=*BST;
Search_BST(&(*BST)->lchild,p,q,key);
}
}
int Insert_BST(BiTree *BST,elemtype key)
{
//int flag=0;
BiTree p,q,s;
p=*BST;
if(Search_BST(BST,&p,&q,key))
{
printf("¸Ãkey=%dÒÑ´æÔÚ\n",key);
flag=0;
}
else
{
s=(BiTree)malloc(sizeof(BiTNode));
s->data=key;
s->lchild=s->rchild=NULL;
if(p==NULL)
{
*BST=s;
}
else if(key<p->data)
{
p->lchild=s;
}
else
{
p->rchild=s;
}
flag=1;
}
return flag;
}
int Create_BST(BiTree *BST,elemtype kx[],int n)
{
for(int i;i<n;i++)
{
Insert_BST(BST,kx[i]);
}
return 1;
}
int main()
{
BiTree BST;
Init_BST(&BST);
BiTree root=BST;
int kx[5]={1,2,3,4,5};
Create_BST(&BST,kx,5);
printf("%d\n",root->data);
return 0;
}