二叉排序树数据结构及操作(BST求中序第一个元素,插入,查找,删除)

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4 // 二叉排序树数据结构
  5 typedef struct BST
  6 {
  7     int data;                    // 数据部分
  8     struct BST *lchild, *rchild; // 左右孩子
  9 } BST, *BSTree;
 10 
 11 // 求中序第一个元素
 12 BSTree first_of_mideum(BSTree bst)
 13 {
 14     while (bst->lchild)
 15         bst = bst->lchild;
 16     return bst;
 17 }
 18 // 插入新元素
 19 bool insert(BSTree &bst, int e)
 20 {
 21     if (bst == NULL)
 22     {
 23         BSTree btemp = (BST *)malloc(sizeof(BST));
 24         btemp->data = e;
 25         btemp->lchild = NULL;
 26         btemp->rchild = NULL;
 27         bst = btemp;
 28     }
 29     if (bst->data == e)
 30         return false;
 31     if (bst->data < e)
 32     {
 33         return insert(bst->lchild, e);
 34     }
 35     else
 36     {
 37         return insert(bst->rchild, e);
 38     }
 39 }
 40 // 创建函数
 41 BSTree createBST(int elements[], int n)
 42 {
 43     BSTree bst = NULL;
 44     int i = 0;
 45     while (i < n)
 46         insert(bst, elements[i++]);
 47     return bst;
 48 }
 49 // 查找函数
 50 bool search(BSTree bst, int e)
 51 {
 52     if (bst == NULL)
 53         return false;
 54     if (bst->data == e)
 55         return true;
 56     else if (bst->data < e)
 57         return search(bst->lchild, e);
 58     else
 59         return search(bst->rchild, e);
 60 }
 61 // 删除函数
 62 bool del(BSTree &bst, int e)
 63 {
 64     if (bst == NULL)
 65         return false;
 66     if (bst->data == e)
 67     {
 68         if (bst->lchild == NULL && bst->rchild == NULL)
 69         {
 70             BSTree btemp = bst;
 71             bst = NULL;
 72             free(btemp);
 73             return true;
 74         }
 75         else if (bst->lchild == NULL)
 76         {
 77             BSTree btemp = bst;
 78             bst = bst->rchild;
 79             free(btemp);
 80             return true;
 81         }
 82         else if (bst->rchild == NULL)
 83         {
 84             BSTree btemp = bst;
 85             bst = bst->lchild;
 86             free(btemp);
 87             return true;
 88         }
 89         else
 90         {
 91             BSTree btemp = first_of_mideum(bst);
 92             BSTree btemp2 = bst;
 93             bst = btemp;
 94             free(btemp2);
 95             del(btemp, btemp->data);
 96         }
 97     }
 98     else if (bst->data < e)
 99         return del(bst->lchild, e);
100     else
101         return del(bst->rchild, e);
102 }
103 int main()
104 {
105     BSTree bst = NULL;
106     int a[] = {1, 2, 3, 4, 5};
107     bst = createBST(a, 5);
108     printf("%d, %d, %d, %d, %d\n", search(bst, 1), search(bst, 2), search(bst, 3), search(bst, 4), search(bst, 5));
109     printf("%d, %d\n", del(bst, 4), del(bst, 8));
110     printf("%d, %d, %d, %d, %d\n", search(bst, 1), search(bst, 2), search(bst, 3), search(bst, 4), search(bst, 5));
111     return 0;
112 }

 

上一篇:BST定义


下一篇:算法与数据结构实验题 6.32 我不会 AVL