Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1883548
  • 博文数量: 217
  • 博客积分: 4362
  • 博客等级: 上校
  • 技术积分: 4180
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-20 09:31
文章分类

全部博文(217)

文章存档

2017年(1)

2015年(2)

2014年(2)

2013年(6)

2012年(42)

2011年(119)

2010年(28)

2009年(17)

分类: C/C++

2011-08-24 15:25:13

    有关二叉排序树的定义是递归定义的。
    1)如果左子树是非空的,则左子树上所有结点的值都小于它的根结点的值;
    2)如果它的右子树是非空的,则右子树上所有结点的值均大于或者等于它的根结点的值;
    3)它的左右子树也分别是二叉排序树。
    如下是有关二叉排序树的创建、插入、查找的算法
  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. #define N 10

  4. typedef struct node {
  5.     int key;
  6.     struct node *lchild, *rchild;
  7. } BSTNode, *BSTtree;

  8. void CreateBST(BSTtree *bst);
  9. void InsertBST(BSTtree *bst, int key);
  10. BSTtree SearchBST(BSTtree bst, int key);

  11. int main()
  12. {
  13.     BSTtree bst;
  14.     BSTtree res;

  15.     CreateBST(&bst);
  16.     res = SearchBST(bst, 122);
  17.     if(res == NULL) {
  18.         printf("not found\n");
  19.         return 0;
  20.     }
  21.     printf("%d\n", res->key);
  22.     return 0;
  23. }

  24. void CreateBST(BSTtree *bst)
  25. {
  26.     int a[N] = {122, 18, 23, 7, 98, 100, 10, 130, 155, 18};
  27.     int i = 0;

  28.     *bst = NULL;
  29.     while(i != N) {
  30.         InsertBST(bst, a[i]);
  31.         i++;
  32.     }
  33. }

  34. void InsertBST(BSTtree *bst, int key)
  35. {
  36. /*插入的递归算法*/
  37.     /*
  38.     BSTtree s;

  39.     if(*bst == NULL) {
  40.         s = (BSTtree)malloc(sizeof(BSTNode));
  41.         s->key = key;
  42.         s->lchild = NULL;
  43.         s->rchild = NULL;
  44.         *bst = s;
  45.     } else if(key < (*bst)->key) {
  46.         InsertBST(&(*bst)->lchild, key);
  47.     } else if(key >= (*bst)->key) {
  48.         InsertBST(&(*bst)->rchild, key);
  49.     }
  50.     */
  51. /*插入的非递归算法*/
  1.     BSTtree tmp, s;
  2.     s = *bst;
  3.     while(s != NULL) {
  4.         if(key < s->key) {
  5.             s = s->lchild;
  6.         } else {
  7.             s = s->rchild;
  8.         }
  9.     }
  10.     tmp = (BSTtree)malloc(sizeof(BSTNode));
  11.     tmp->key = key;
  12.     tmp->lchild = NULL;
  13.     tmp->rchild = NULL;
  14.     s = tmp;
  15. }

  16. BSTtree SearchBST(BSTtree bst, int key)
  17. {
  18. /*查找的递归算法*/
  19.     /*
  20.     if(bst == NULL) {
  21.         return NULL;
  22.     } else if(bst->key == key) {
  23.         return bst;
  24.     } else {
  25.         if(bst->key > key) {
  26.             return SearchBST(bst->lchild, key);
  27.         } else {
  28.             return SearchBST(bst->rchild, key);
  29.         }
  30.     }
  31.     */
  32.     BSTtree q;

/*查找的非递归算法*/
  1.     q = bst;
  2.     while( NULL) {
  3.         if(q->key == key) {
  4.             break;
  5.         } else if(q->key > key) {
  6.             q = q->lchild;
  7.         } else {
  8.             q = q->rchild;
  9.         }
  10.     }
  11.     return q;
  12. }


阅读(1534) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~