#include<iostream.h>
#include<malloc.h>
struct node
{
int num;
node *left;
node *right;
};
void creatree(node *&p,int a[],int start,int end)//使用*&p的原因
//要在函数体内修改形参的值,并且这个修改能作用到外面调用的实参,用单独的指针就不行,只能用指针的引用或者指针的指针
{
if(start<=end)
{
int m=(start+end)/2;
p = (node *)malloc(sizeof(node));
p->num=a[m];
p->left=NULL;
p->right=NULL;
creatree(p->left,a,start,m-1);
creatree(p->right,a,m+1,end);
}
else
return;
}
int searchmin(node *p)//排序树因此顺着左子树就能找到最小值
{
if(p!=NULL)
{
while(p->left!=NULL)
p=p->left;
return p->num;
}
}
int searchmax(node *p)//排序树因此顺着右子树就能找到最大值
{
if(p!=NULL)
{
while(p->right!=NULL)
p=p->right;
return p->num;
}
}
int searchnumber(node *p,int f)//与f最近而且大于f
/*
因为是有序的二叉树故可以和节点比较,如果大于此节点则向右子树查找
如果小于此节点则向坐子树查找,最后开始回溯,取大于f的第一个数
n就是返回值大于f的个数,初始是零,回溯过程中出现大于f的值时,输出此数值
然后n加1,就不必输出此后面的值,因为要求最接近的一个数值
*/
{
if(p!=NULL)
{
int n=0;
if(f>=p->num)
n=searchnumber(p->right,f);
else
n=searchnumber(p->left,f);
if(n==0&&p->num>f)
{
cout<<p->num<<endl;
return n+1;
}
else
return n;
}
else
return 0;
}
void main()
{
int a[10]={1,4,6,7,10,13,14,18,21,30};
node *root=NULL;
creatree(root,a,0,sizeof(a)/sizeof(int)-1); //创建树
int min=searchmin(root);
int max=searchmax(root);
searchnumber(root,(max+min)/2);
}
一颗排序二叉树,令f=(最大值+最小值)/2,找出距离f值最近、大于f值的结点
最新推荐文章于 2021-09-13 21:52:01 发布