基于C语言实现排序二叉树BST基本操作,具体包括:
- 增加节点
- 创建BST
- 删除节点:(1)首先通过比较大小查找到待删除位置(2)删除时进行孩子节点分析:无孩子,直接删掉;1个孩子,当前节点的父节点和孩子节点相连后再删除;2个孩子,用左子树的最后或右子数的最左来替换待删除节点,然后继续孩子节点分析的过程。
#include <stdlib.h>
#include <stdio.h>
typedef struct tree
{
int nValue;
struct tree *pLeft;
struct tree *pRight;
}BST;
//增加节点
void AddNode(BST **pTree, int num)
{
BST *pTemp = (BST*)malloc(sizeof(BST));
pTemp->nValue = num;
pTemp->pLeft = NULL;
pTemp->pRight = NULL;
if(*pTree == NULL)
{
*pTree = pTemp;
return;
}
BST *pNode = *pTree;
while(pNode != NULL)
{
if(num > pNode->nValue)
{
if(pNode->pRight == NULL)
{
pNode->pRight = pTemp;
break;
}
pNode = pNode->pRight;
}
else if(num < pNode->nValue)
{
if(pNode->pLeft == NULL)
{
pNode->pLeft = pTemp;
break;
}
pNode = pNode->pLeft;
}
else
{
printf("data erro\n");
exit(1);
}
}
}
//创建BST
BST *CreateBST(int arr[], int nLength)
{
if(arr == NULL || nLength <= 0) return NULL;
BST *pTree = NULL;
int i;
for(i=0;i<nLength;i++)
{
AddNode(&pTree, arr[i]);
}
return pTree;
}
void Traversal(BST *pTree)
{
if(pTree == NULL) return;
Traversal(pTree->pLeft);
printf("%d ", pTree->nValue);
Traversal(pTree->pRight);
}
//查找待删除节点
void Search(BST *pTree, int nNum, BST **pFat, BST **pDel)
{
while(pTree)
{
if(pTree->nValue == nNum)
{
*pDel = pTree;
break;
}
else if(pTree->nValue < nNum)
{
*pFat = pTree;
pTree = pTree->pRight;
}
else
{
*pFat = pTree;
pTree = pTree->pLeft;
}
}
*pFat = NULL;
}
//删除节点
void DelNode(BST **pTree, int nNum)
{
BST *pDel = NULL;
BST *pFat = NULL;
Search(*pTree, nNum, &pFat, &pDel);
if(pDel == NULL) return;
BST *pMark = NULL;
if(pDel->pLeft != NULL || pDel->pRight != NULL)
{
pMark = pDel;
//找左的最右
pFat = pDel;
pDel = pDel->pLeft;
while(pDel->pRight != NULL)
{
pFat = pDel;
pDel = pDel->pRight;
}
pMark->nValue = pDel->nValue;
}
//根
if(pFat == NULL)
{
*pTree = pDel->pLeft ? pDel->pLeft : pDel->pRight;
free(pDel);
pDel = NULL;
return;
}
if(pDel == pFat->pLeft)
{
pFat->pLeft = pDel->pLeft ? pDel->pLeft : pDel->pRight;
}
else
{
pFat->pRight = pDel->pLeft ? pDel->pLeft : pDel->pRight;
}
free(pDel);
pDel = NULL;
}
int main()
{
BST *pTree = NULL;
int arr[] = {5,1,32,19,128,45};
pTree = CreateBST(arr, sizeof(arr)/sizeof(arr[0]));
Traversal(pTree);
printf("\n");
DelNode(&pTree, 32);
Traversal(pTree);
printf("\n");
return 0;
}