二叉排序树(BST)的查找算法(递归算法)

#include <iostream>
using namespace std;

// BST的结点
typedef struct node
{
	int key;
	struct node *lChild, *rChild;
}Node, *BST;

// 在给定的BST插入element, 使之称为新的BST
bool BSTInsert(Node * &p, int element)
{
	if(NULL == p) // 空树
	{
		p = new Node;
		p->key = element;
		p->lChild = p->rChild = NULL;
		return true;
	}

	if(element == p->key) // BST中不能有相等的值
		return false;

	if(element < p->key)  // 递归
		return BSTInsert(p->lChild, element);

	return BSTInsert(p->rChild, element); // 递归
}

// 建立BST
void createBST(Node * &T, int a[], int n)
{
	T = NULL; 
	int i;
	for(i = 0; i < n; i++)
	{
		BSTInsert(T, a[i]);
	}
}

// BST的查找(递归)
Node *BSTSearch(BST T, int x)
{
	if(NULL == T)
		return NULL;

	if(x == T->key)
		return T;

	if(x < T->key)
		return BSTSearch(T->lChild, x);

	return BSTSearch(T->rChild, x);
}

int main()
{
	int a[10] = {4, 5, 2, 1, 0, 9, 3, 7, 6, 8};
	int n = 10;

	BST T = NULL;

	// 并非所有的a[]都能构造出BST,所以,最好对createBST的返回值进行判断
	createBST(T, a, n);
	
	Node *p = NULL;
	
	int x; // 待查找的x
	for(x = -10; x < 20; x++)
	{
		p = BSTSearch(T, x);
		cout << x << ":";
		if(NULL == p)
			cout << "no" << endl;
		else
			cout << "yes" << endl;
	}

	return 0;
}

       结果为:

-10:no
-9:no
-8:no
-7:no
-6:no
-5:no
-4:no
-3:no
-2:no
-1:no
0:yes
1:yes
2:yes
3:yes
4:yes
5:yes
6:yes
7:yes
8:yes
9:yes

10:no
11:no
12:no
13:no
14:no
15:no
16:no
17:no
18:no
19:no
Press any key to continue

  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值