#include <iostream>
using namespace std;
typedef struct BTNode
{
int key;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
//二叉排序树的关键字查找
BTNode* BSTSearch(BTNode* bt, int key)
{
if (bt == NULL)
return NULL;
if (bt->key == key)
return bt; //返回关键字所在的结点指针
else if(bt->key > key)
return BSTSearch(bt->lchild, key);
else
return BSTSearch(bt->rchild, key);
}
//二叉排序树的结点的插入
int BSTInsert(BTNode *&bt, int key)
{
if (bt == NULL)
{
//当前为空指针说明找到了插入位置,创建新结点在此插入
bt = (BTNode*)malloc(sizeof(BTNode));
bt->lchild = bt->rchild = NULL;
bt->key = key;
return 1;
}
else
{
if (bt->key == key)
return 0; //该关键字已经存在,插入失败
else if(bt->key > key)
return BSTInsert(bt->lchild, key);
else
return BSTInsert(bt->rchild, key);
}
}
//二叉排序树的构造
void createBST(BTNode *&bt, int key[], int n)
{
int i;
bt = NULL;
for (i = 0; i < n; ++i)
{
BSTInsert(bt, key[i]);
}
}
int main()
{
BTNode *bt;
int key[] = {3, 4, 5, 7, 8, 9, 10};
int n = 7;
createBST(bt, key, n);
BTNode *p;
p = BSTSearch(bt, 6);
if (p == NULL)
cout << "没有找到" << endl;
else
cout << "找到了 " << p->key << endl;
int res = BSTInsert(bt, 6);
cout << res << endl;
p = BSTSearch(bt, 6);
if (p == NULL)
cout << "没有找到" << endl;
else
cout << "找到了 " << p->key << endl;
return 0;
}
输出结果: