二插排序树的建立

// 二插排序树的建立.cpp : 此文件包含 “main” 函数。程序执行将在此处开始并结束。
//
#include
using namespace std;
class link
{
public:
int data;
link *lchild,*rchild;
};
int b[] = { 0,32,75,29,63,48,94,25,4,18,7 };
const int n = 10;
int count1=0;
void insert(link * &bst, int x)//插入值为x的结点
{
if (bst == NULL)
{
link *p;
p = new link;
p->data = x;
p->lchild = p->rchild = NULL;
bst = p;
}
else
{
if (bst->data >= x)insert(bst->lchild, x);
else insert(bst->rchild, x);
}
}
link * creat(int r[], int n)//二叉树的创建
{
int i; link *bst=NULL;
for (i = 1; i <= n; i++)
{
insert(bst, r[i]);
}
return bst;
}
link *search(link *&bst, int x)//二插树查找函数
{
if (bst == NULL)return NULL;
else
{
link *p = bst;
while (p != NULL)
{
if (p->data == x)break;
else if (p->data > x)
{
p = p->lchild;
count1++;
}
else
{
p = p->rchild;
count1++;
}
}
if (p != NULL)return p;
else return NULL;
}
}
void inorder(link *root)//中序遍历
{
link *s;
s = root;
if (s != NULL)
{
inorder(s->lchild);
cout << s->data << " ";
inorder(s->rchild);
}
}
void operate()
{
int k2;
link *t,*p1;
cout << “初始序列:” << endl;
for (int i = 1; i <= n; i++)
cout << b[i] << " ";
cout << endl;
cout << “建立二叉排序树:” << endl;
t=creat(b, n);
cout << “中序遍历:” << endl;
inorder(t);
cout << endl;
cout << "请输入要查找的内容: ";
cin >> k2;
p1 = search(t, k2);
if (p1!= NULL)
{
cout << “查找成功!”;
cout << “比较次数是:” << count1 << endl;
}
else
{
cout << “不存在!” << endl;
cout << “比较次数是:” << count1 << endl;
}
count1 = 0;
}
void main()
{
operate();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值