二叉排序樹查詢,插入,刪除

dongyu2013發表於2014-04-11

點選(此處)摺疊或開啟

  1. typedef struct BiTNode
  2. {
  3.     int data;
  4.     struct BiTNode *lchild, *rchild;
  5. }BiTNode, *BiTree;

  6. //遞迴查詢二叉排序樹T中是否存在key
  7. //指標f指向T的雙親,其初始化呼叫值為NULL
  8. //若查詢成功,則指標p指向該資料元素節點,並返回TURE
  9. //否則指標p指向查詢路徑上訪問的最後一個節點並返回FALSE
  10. bool SearchBST(BiTree T, int key, BiTree f, BiTree *p)
  11. {
  12.     if(!T)
  13.     {
  14.         *p=f;
  15.         return FALSE;
  16.     }
  17.     else if(key==T->data)
  18.     {
  19.      *p=T;
  20.         return TRUE;
  21.     }
  22.     else if(key<T->data)
  23.     {
  24.         return SearchBST(T->lchild, key, T, p);
  25.     }
  26.     else
  27.     {
  28.         return SearchBST(T->rchild, key, T, p);
  29.     }
  30. }

  31. //當二叉樹排序樹T中不存在關鍵字等於key的資料元素時
  32. //插入key並返回TRUE, 否則返回FALSE

  33. bool InsertBST(BiTree *T, int key)
  34. {
  35.     BiTree p,s;
  36.     if(!SearchBST(*T, key, NULL, &p))
  37.     {
  38.         s=(BiTree)malloc(sizeof(BiTNode));
  39.         s->data=key;
  40.         s->lchild=s->rchild=NULL;
  41.         if(!p)
  42.         {
  43.             *T=s;
  44.         }
  45.         else if(key<p->data)
  46.         {
  47.             p->lchild=s;
  48.         }
  49.         else
  50.         {
  51.             p->rchild=s;
  52.         }
  53.         return true;
  54.     }
  55.     else
  56.     {
  57.         return false;
  58.     }
  59. }


  60. bool Delete(BiTree *p)
  61. {
  62.     BiTree q,s;
  63.     if( (*p)->rchild==NULL )
  64.     {
  65.         q=*p; *p=(*p)->lchild; free(q);
  66.     }
  67.     else if( (*p)->lchild==NULL )
  68.     {
  69.         q=*p; *p=(*p)->rchild; free(q);
  70.     }
  71.     else
  72.     {
  73.         q=*p; s=(*p)->lchild;
  74.         while(s->rchild)
  75.         {
  76.             q=s; s=s->rchild;
  77.         }
  78.         (*p)->data=s->data;
  79.         if(q!=*p)
  80.             q->rchild=s->lchild;
  81.         else
  82.             q->lchild=s->rchild;
  83.     }
  84.     return true;
  85. }


  86. bool DeleteBST(BiTree *T, int key)
  87. {
  88.     if(!*T)
  89.     {
  90.         return false;
  91.     }
  92.     else
  93.     {
  94.         if(key==(*T)->data)
  95.         {
  96.             return Delete(T);
  97.         }
  98.         else if (key<(*T)->data)
  99.         {
  100.             return DeleteBST(&(*T)->lchild, key);
  101.         }
  102.         else
  103.         {
  104.             return DeleteBST(&(*T)->rchild, key);
  105.         }
  106.     }
  107. }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29012686/viewspace-1140292/,如需轉載,請註明出處,否則將追究法律責任。

相關文章