標籤:turn The return nod void binary search 排序 fat
要點:
1.尋找到被刪除的節點
2.分析要刪除的節點
1.葉子結點
2.有一個孩子
3.有兩個孩子(根節點和其他節點)
代碼實現:
void SearchNode(Tree** pDel,Tree** pFather,int num){ while(*pDel) { if((*pDel)->val == num) return; else if((*pDel)->val > num) { *pFather = *pDel; *pDel = (*pDel)->pleft; } else { *pFather = *pDel; *pDel = (*pDel)->pright; } } *pDel = NULL;}void DelNode(Tree** pRoot,int num){ Tree* pDel = *pRoot; Tree* pFather = NULL; SearchNode(&pDel,&pFather,num); if(pDel == NULL)//沒找到 return; Tree* pMark = NULL; //有兩個孩子 if(pDel->pleft != NULL && pDel->pright != NULL) { pMark = pDel; pFather = pDel; pDel = pDel->pleft; while(pDel) { pFather = pDel; pDel = pDel->pright; } pMark->val = pDel->val; } //只有一個孩子或者沒有孩子 if(pDel == *pRoot) {//根只有一個孩子或者沒有孩子 *pRoot = pDel->pleft ? pDel->pleft : pDel->pright; } if(pDel == pFather->pleft) pFather->pleft = pDel->pleft ? pDel->pleft : pDel->pright; if(pDel == pFather->pright) pFather->pright = pDel->pleft ? pDel->pleft : pDel->pright; free(pDel); pDel = NULL;}
其中尋找函數Search可以傳入多一個參數:
void FindNode(BinaryTree *pTree,int nNum,BinaryTree **pDel,BinaryTree **pFather){ while(pTree) { if(pTree->nValue == nNum) { *pDel = pTree; return; } else if(pTree->nValue > nNum) { *pFather = pTree; pTree = pTree->pLeft; } else { *pFather = pTree; pTree = pTree->pRight; } } *pFather = NULL;}void DelNode(BinaryTree **pTree,int nNum){ if(*pTree == NULL)return; //尋找 BinaryTree *pDel = NULL; BinaryTree *pFather = NULL; FindNode(*pTree,nNum,&pDel,&pFather); //分析被刪除節點情況 if(pDel == NULL)return; //兩個孩子 BinaryTree *pMark = NULL; if(pDel->pLeft != NULL && pDel->pRight != NULL) { pMark = pDel; //左的最右 pFather = pDel; pDel = pDel->pLeft; while(pDel->pRight != NULL) { pFather = pDel; pDel = pDel->pRight; } //值覆蓋 pMark->nValue = pDel->nValue; } //刪除有一個孩子或者0個孩子 if(pFather == NULL) { //根 *pTree = pDel->pLeft?pDel->pLeft:pDel->pRight; free(pDel); pDel = NULL; return; } if(pDel == pFather->pLeft) { pFather->pLeft = pDel->pLeft?pDel->pLeft:pDel->pRight; } else { pFather->pRight = pDel->pLeft?pDel->pLeft:pDel->pRight; } free(pDel); pDel = NULL;}
排序二叉樹節點的刪除