1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
| #include <stdio.h> #include <malloc.h> typedef int KeyType; typedef char InfoType[10]; typedef struct node { KeyType key; InfoType data; struct node *lchild,*rchild; } BSTNode; bool InsertBST(BSTNode *&bt,KeyType k)
{ if (bt==NULL) { bt=(BSTNode *)malloc(sizeof(BSTNode)); bt->key=k; bt->lchild=bt->rchild=NULL; return true; } else if (k==bt->key) return false; else if (k<bt->key) return InsertBST(bt->lchild,k); else return InsertBST(bt->rchild,k); }
BSTNode *CreateBST(KeyType A[],int n)
{ BSTNode *bt=NULL; int i=0; while (i<n) { InsertBST(bt,A[i]); i++; } return bt; }
void DispBST(BSTNode *bt) { if (bt!=NULL) { printf("%d",bt->key); if (bt->lchild!=NULL || bt->rchild!=NULL) { printf("("); DispBST(bt->lchild); if (bt->rchild!=NULL) printf(","); DispBST(bt->rchild); printf(")"); } } } BSTNode *SearchBST(BSTNode *bt,KeyType k) { if (bt==NULL || bt->key==k) return bt; if (k<bt->key) return SearchBST(bt->lchild,k); else return SearchBST(bt->rchild,k); } BSTNode *SearchBST1(BSTNode *bt,KeyType k,BSTNode *f1,BSTNode *&f)
{ if (bt==NULL) { f=NULL; return(NULL); } else if (k==bt->key) { f=f1; return(bt); } else if (k<bt->key) return SearchBST1(bt->lchild,k,bt,f); else return SearchBST1(bt->rchild,k,bt,f); }
void Delete1(BSTNode *p,BSTNode *&r) { BSTNode *q; if (r->rchild!=NULL) Delete1(p,r->rchild); else { p->key=r->key; q=r; r=r->lchild; free(q); } } void Delete(BSTNode *&p) { BSTNode *q; if (p->rchild==NULL) { q=p; p=p->lchild; free(q); } else if (p->lchild==NULL) { q=p; p=p->rchild; free(q); } else Delete1(p,p->lchild); } int DeleteBST(BSTNode *&bt,KeyType k) { if (bt==NULL) return 0; else { if (k<bt->key) return DeleteBST(bt->lchild,k); else if (k>bt->key) return DeleteBST(bt->rchild,k); else { Delete(bt); return 1; } } } void DestroyBST(BSTNode *&bt) { if (bt!=NULL) { DestroyBST(bt->lchild); DestroyBST(bt->rchild); free(bt); } }
|