// 二插排序树的建立.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();
}
二插排序树的建立
最新推荐文章于 2022-05-08 21:32:41 发布