排序二叉树BST的基本操作

基于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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值