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

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               
#include <iostream>using namespace std;// BST的结点typedef struct node{ int key; struct node *lChild, *rChild;}Node, *BST;// 在给定的BST插入element, 使之称为新的BSTbool 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 falseif(element < p->key)  // 递归  return BSTInsert(p->lChild, element); return BSTInsert(p->rChild, element); // 递归}// 建立BSTvoid 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 NULLif(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

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值