/*二叉查找树*/
#include<stdio.h>
//定义几个结构体
struct BiNode //定义一个结构体
{
int data;
BiNode *lchild,*rchild;
};
BiNode *InsertBST(BiNode *root,int dat);
BiNode *CreateBST(int a[],int n);
BiNode *SearchBST(BiNode* root,int k);
//主函数
main()
{
int r[]={10,83,45,67,41,58,70,90,55};
int s=0;
BiNode *T;
BiNode *P;
T=CreateBST(r,9);
P=SearchBST(T,58);
if(P!=NULL)
{
printf("找到了");
}
else {
printf("没找到");
}
}
//在二叉树插入节点
BiNode *InsertBST(BiNode *root,int data)
{
if(root==NULL)
{
root=new BiNode; //为data申请一个新节点
root->data=data;
return root;
}
if(data<=root->data) //插在root的左子树
root->lchild=InsertBST(root->lchild,data);
else //插在root的左子树
root->rchild=InsertBST(root->rchild,data);
return root;
}
//将无序序列a[n]建立二叉查找树
BiNode *CreateBST(int a[],int n)
{
BiNode *T=NULL;
for(int i=0; i<n; i++)
{
T=InsertBST(T,a[i]);
}
return T;
}
//查找二叉树
BiNode *SearchBST(BiNode* root,int k)
{
if(root==NULL) return NULL; //二叉查树数为空,查找失败
else if(root->data==k) return root; //查找成功
else if(k<root->data) //查找左子树
return SearchBST(root->lchild,k);
else //查找右子树
return SearchBST(root->rchild,k);
}
减治法———二叉查找树(未完成)
最新推荐文章于 2023-03-17 07:30:00 发布