引用头文件:
#include <stdio.h>
#include <stdlib.h>
定义其节点类型:
typedef struct node
{
int key;
struct node *lchild;
struct node *rchild;
}BSTNode;
二叉搜索树的插入:
int InsertBST(BSTNode *&p,int k)//插入关键字,插入成功返回1,否则返回0;
{
if(p==NULL)//原树为空,新插入的元素为根节点;
{
p=(BSTNode *)malloc(sizeof(BSTNode));
p->key=k;
p->lchild=p->rchild=NULL;
return 1;
}
else if(k==p->key)//树中存在相同关键字的节点,返回0;
{
return 0;
}
else if(k<p->key)
{
return InsertBST(p->lchild,k);
}
else
return INsertBST(p->rchild,k);
}
二叉树的生成:
BSTNode * CreateBST(int data[],int n)
{
BSTNode *bt=NULL;//初始时为空树;
int i=0;
while(i<n)
{
InsertBST(bt,data[i]);//将关键字data[i]插入二叉排序树bt中;
i++;
}
return bt;//返回建立的二叉排序树的根指针;
}
二叉排序树的查找:
BSTNode * SearchBST(BSTNode *bt,int k)
{
if(bt==NULL||bt->key==k)//递归终结条件;成功时返回找到的元素的节点指针;
{
return bt;
}
if(k<bt->key)
{
return SearchBST(bt->lchild,k);
}
else
{
return SearchBST(bt->rchild,k);
}
}
主函数:
int main()
{
int n,i;
int data[1000];
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
int item;
scanf("%d",&item);
BSTNode *head;
head=CreateBST(data,n);
BSTNode *p;
p=SearchBST(head,item);
return 0;
}