二叉查找树

本文介绍了二叉查找树的基本操作实现,包括递归与非递归查找、查找最小及最大元素、插入与删除节点等关键算法。通过具体代码示例,详细展示了每种操作的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//二叉查找树的实现
struct Node
{
	int data;
	Node *lchild,*rchild,*parent;
};
//在以t为树根的二叉查找树中,递归查找关键字key
Node* recursion_tree_search(Node *t,int key)
{
	if(t!=NULL || key==t->data)
		return t;
	if(key<t->data)
		return recursion_tree_search(t->lchild,key);
	else
		return recursion_tree_search(t->rchild,key);
}
//在以t为树根的二叉查找树中,非递归查找关键字key
Node* iterative_tree_search(Node *t,int key)
{
	while(t!=NULL && key!=t->data)
		t=(key<t->data)?t->lchild:t->rchild;
	return t;
}
//在以t为树根的二叉查找树中,查找最小元素,返回其指针
Node* tree_minimum(Node *t)
{
	while(t->lchild!=NULL)
		t=t->lchild;
	return t;
}
//在以t为树根的二叉查找树中,查找最大元素,返回其指针
Node* tree_maxmum(Node *t)
{
	while(t->rchild!=NULL)
		t=t->rchild;
	return t;
}
//查找x节点的直接后继,返回其指针
Mode* tree_successor(Node *x)
{
	if(x->rchild!=NULL)
		return tree_minimum(x->rchild);
	else
	{
		Node *p=x->parent;
		while(p!=NULL && x==p->rchild)
		{
			x=p;
			p=p->parent;
		}
		return p;
	}
}
//查找x结点的直接前驱,返回其指针
Node *tree_predecessor(Node *x)
{
	if(x->lchild!=NULL)
		return tree_maxmum(x->lchild);
	else
	{
		Node *p=x->parent;
		while(p!=NULL && x==p->lchild)
		{
			x=p;
			p=p->parent;
		}
		return p;
	}
}
//在以t为树根的二叉查找树中,插入结点
void tree_insert(Node *t,Node *x)
{
	Node *p=NULL;
	while(t!=NULL)
	{
		p=t;
		if(x->data<t->data)
			t=t->lchild;
		else
			t=t->rchild;
	}
	if(p==NULL)
		t=x;
	else if(x->data<p->data)
	{
		p->lchild=x;
		x->parent=p;
	}
	else
	{
		p->rchild=x;
		x->parent=p;
	}
}
//在以t为树根的二叉查找树中,删除关键字为key的结点
Node* tree_delete(Node *t,int key)
{
	Node *x=iterative_tree_search(t,key);//x指向被删除的真正结点
	Node *y,*z;
	if(x->lchild==NULL || x->rchild==NULL)
		y=x;//y指向x
	else
		y=tree_successor(x);//y指向x的后继结点
	if(y->lchild!=NULL)
		z=y->lchild;//z指向被删除结点的左孩子
	else
		z=y->rchild;//z指向被删除结点的右孩子
	if(z!=NULL)
		z->parent=y->parent;//修改结点
	if(y->parent==NULL)//y为根结点
		t=z;
	else if(y==y->parent->lchild)
		y->parent->lchild=z;
	else
		y->parent->rchild=z;
	if(y!=x)//y指向后继结点 交换
		x->data=y->data;
	return y;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值