1 #include"stdio.h" 2 #include"malloc.h" 3 typedef int elemtype; 4 typedef struct btnode 5 { 6 elemtype data;/*關鍵字域*/ 7 struct btnode *lchild,*rchild; 8 }btnode,*bitree; 9 int searchBST(bitree t, elemtype key, bitree f,bitree *p) 10 /*遞歸查找二叉排序樹t是否存在key,指針f指向t的雙親,其初始調用值為NULL,若查找成功, 11 則指針p指向該數據元素結點並返回1,否則指針p指向查找路徑上訪問的最后一個結點並返回0*/ 12 { 13 if (!t){ *p=f; return 0;}//查找不成功 14 else if(key==t->data)//查找成功 15 { 16 *p=t; 17 return 1; 18 } 19 else if(key<t->data) 20 return searchBST(t->lchild,key,t,p);//在左子樹繼續查找 21 else 22 return searchBST(t->rchild,key,t,p);//在右子樹繼續查找 23 } 24 25 int insertBST(bitree *t, elemtype key) 26 /*當二叉排序樹T中不存在關鍵字等於key的數據元素時,插入key返回二叉排序樹的根結點。*/ 27 { 28 bitree p,s; 29 if (!searchBST(*t,key,NULL,&p)) /*查找不成功*/ 30 { 31 s=(bitree)malloc(sizeof(btnode)); 32 s->data=key; 33 s->lchild = s->rchild = NULL; 34 if (!p) *t=s; /*插入s為新的根結點*/ 35 else if ( key< p->data) 36 p->lchild=s; /*插入s為左孩子*/ 37 else 38 p->rchild=s; /*插入s為右孩子*/ 39 return 1; 40 } 41 else 42 return 0; 43 } 44 void inorder(bitree bt) //中序遍歷 45 { 46 if(bt==NULL)return; 47 else{ 48 inorder(bt->lchild); 49 printf("%d ",bt->data); 50 inorder(bt->rchild); 51 } 52 } 53 /*若二叉排序樹存在關鍵字等於key的數據元素時,則刪除該數據元素結點*/ 54 int deleteBST(bitree *t, elemtype key) 55 { 56 if(!*t)//不存在關鍵字等於key的數據元素 57 return 0; 58 else 59 { 60 if(key==(*t)->data) 61 return delete(t); 62 else if(key<(*t)->data) 63 return deleteBST(&(*t)->lchild,key); 64 else 65 return deleteBST(&(*t)->rchild,key); 66 } 67 } 68 int delete(bitree *p) 69 { 70 bitree q,s; 71 if((*p)->rchild==NULL)//右子樹空則只需重接它的左子樹 72 { 73 q=*p;*p=(*p)->lchild;free(q); 74 } 75 else if((*p)->lchild==NULL)//只需重接它的右子樹 76 { 77 q=*p;*p=(*p)->rchild;free(q); 78 } 79 else//左右子樹都不空 80 { 81 q=*p;s=(*p)->lchild; 82 while(s->rchild){//轉左,然后向右到盡頭 83 q=s;s=s->rchild; 84 85 } 86 (*p)->data=s->data;//s指向被刪結點的直接前驅 87 if(q!=*p) 88 q->rchild=s->lchild;//重接q的右子樹 89 else 90 q->lchild=s->lchild;//重接q的左子樹 91 free(s); 92 } 93 return 1; 94 } 95 int main() 96 { 97 int i;bitree f=NULL,p; 98 int a[10]={62,88,58,47,35,73,51,99,37,93}; 99 bitree t=NULL; 100 for(i=0;i<10;i++) 101 { 102 insertBST(&t, a[i]);//插入 103 } 104 inorder(t); 105 printf("\n"); 106 if(searchBST(t,88,f,&p)==1); 107 printf("查找成功,p已指向該元素!"); 108 deleteBST(&t,37);//刪除 109 printf("\n刪除后:\n"); 110 inorder(t); 111 printf("\n"); 112 return 0; 113 }