二叉数组的创建删除插入查找

#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode *BinTree;   //定义一个对象指针
typedef BinTree Position;           //定义一个对象指针名
struct TreeNode{
	int Data;
	BinTree Left;
	BinTree Right;
};

//二叉搜索数的查找Find   
Position Find(int x,BinTree BST)
{
	if(!BST)          //判断BST是否为空
		return NULL;
	if(x > BST->Data)
		return Find(x,BST->Right); //在右指数继续查找
	else if(x < BST->Data)         //在左指数继续查找
		return Find(x,BST->Left);
	else
		return BST;                //查找成功
}

//二叉搜索数的查找Find  非递归实现
Position IterFind(int x,BinTree BST)
{
	while(BST)
	{
		if(x > BST->Data)
			BST = BST->Right;
		else if(x < BST->Data)
			BST = BST->Left;
		else
			return BST;
	}
	return NULL;
}

Position FindMin(BinTree BST)
{
	if(!BST)
		return NULL;
	else if(!BST->Left)     //找到左叶结点并返回
		return BST;
	else
		return FindMin(BST->Left);
}

Position FindMax(BinTree BST)
{
	if(BST)
		while(BST->Right)
			BST = BST->Right;
	return BST;
}

//二叉搜索数的插入算法 适用于带头结点的二叉树
BinTree Insert(int x,BinTree BST)
{
	if(!BST)       //判断传入指针是否为空
	{
		BST = new TreeNode;
		BST->Data = x;
		BST->Left = BST->Right = NULL;
	}else 
		if(x < BST->Data)
			BST->Left = Insert(x,BST->Left);
		else if(x > BST->Data)
			BST->Right = Insert(x,BST->Right);
	return BST;   //如果都不执行就返回
}

//搜索二叉数的删除
BinTree Delete(int x,BinTree BST)
{
	Position Tmp;
	if(!BST)
		printf("删除的元素未找到");
	else if(x < BST->Data)
		BST->Left = Delete(x,BST->Left);
	else if(x > BST->Data)
		BST->Right = Delete(x,BST->Right);
	else
	{
		if(BST->Left&&BST->Right)   //被删除的结点含有左右两个子结点
		{
			Tmp = FindMin(BST->Right);   //在右指数中去找最小值替代被删除元素
			BST->Data = Tmp->Data;
			BST->Right = Delete(BST->Data,BST->Right);  //在删除元素的右边去把最小值那个结点删除掉
		}
		else
		{
			Tmp = BST;
			if(!BST->Left)         //有右孩纸或无结点
				BST = BST->Right;
			else if(!BST->Right)
				BST = BST->Left;		//有左孩纸或无结点
			free(Tmp);
		}

	}
	return BST;
}

void showBinTree(BinTree BST)
{
	if(BST)         //用if判断便于返回
	{
		showBinTree(BST->Left);
		showBinTree(BST->Right);
		printf("%d\n",BST->Data);
	}
	
}

int main()
{
	TreeNode *a = new TreeNode;
	a->Data = 9;
	a->Left = NULL;
	a->Right = NULL;
	a = Insert(5,a);
	a = Insert(6,a);
	a = Insert(10,a);
	a = Insert(13,a);
	a = Delete(5,a);
	showBinTree(a);
	system("pause");
}

//测试数据  1 5 2 6 4
//测试数据  9 5 6 10 13

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值