二叉排序树的构造、插入结点、查找

#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;
}

输出结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值