搜索二叉树的基本操作(增加,删除,查找)递归与非递归算法

二叉搜索树概念:

二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的
二叉树
1.若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
2.若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
3。它的左右子树也分别为二叉搜索树

建立结构体:
typedef int Datatype;
typedef struct BSTreeNode 
{
	struct BSTreeNode *_left;
	struct BSTreeNode *_right;
	Datatype _data;
}BSTreeNode;

创建一个节点:
BSTreeNode *BuyNode(Datatype x)//建立一个节点
{
	BSTreeNode *node=(BSTreeNode *)malloc(sizeof(BSTreeNode));
	assert(node);
	node->_data=x;
	node->_left=NULL;
	node->_right=NULL;
	return node;
}

搜索二叉树的增加(非递归):
int BSTreeInsert(BSTreeNode **tree,Datatype x)//搜索二叉树的插入
{
	BSTreeNode *cur=*tree;
	BSTreeNode *parent=NULL;//应用与插入的前一个节点,方便于连接
	if (*tree==NULL)
	{
		*tree=BuyNode(x);
		return 0;
	}
	while (cur)
	{
		if (cur->_data > x)
		{
			parent=cur;
			cur=cur->_left;
		}
		else if (cur->_data < x)
		{
			parent=cur;
			cur=cur->_right;
		} 
		else
		{
			return -1;//如果二叉树里有相同的值则返回 -1
		}
	}
	if (parent->_data < x)
	{
		parent->_right=BuyNode(x);
	}
	else
	{
		parent->_left=BuyNode(x);
	}
//	return -1;
}

搜索二叉树的增加(递归):
int BSTreeInsertR(BSTreeNode **tree,Datatype x)//递归算法 搜索二叉树的插入
{
	if (*tree==NULL)
	{
		*tree=BuyNode(x);
		return 0;
	}
	if ((*tree)->_data > x)
	{
		return BSTreeInsertR(&(*tree)->_left,x);
	}
	else if ((*tree)->_data < x)
	{
		return BSTreeInsertR(&(*tree)->_right,x);
	}
	else return -1;
}

搜索二叉树的删除(非递归):
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值