二叉查找树

本文深入探讨了二叉查找树的基本操作,包括创建、查找、插入和删除等关键算法。通过递归和非递归方式实现,为读者提供了丰富的代码实例,帮助理解二叉树的动态管理。

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

二叉查找树

创建二叉树

#include<stdio.h>
#include<stdlib.h>
typedef struct BNode{
	char data;
	struct BNode *left,*right;
}BNode,*Bitree;
void CreateTree(Bitree &T)
{
	char c;
	scanf("%c",&c);
	if(c=='.') T=NULL;
	else
	{
		T=(Bitree)malloc(sizeof(BNode));
		T->data=c;
		CreateTree(T->left);
		CreateTree(T->right);
	}
}

查找

Bitree Find_s(Bitree T,char x)//查找元素 
{
	if(T==NULL) return NULL;
	Bitree p=T;
	while(p)
	{
		if(x<p->data) p=p->left;
		else if(x>p->data) p=p->right;
		else return p;
	 }
	 return NULL;
}
Bitree Find(Bitree T,char x)//查找元素(递归)
{
	if(T==NULL) return NULL;
	if(x<T->data) return Find(T->left,x);
	else if(x>T->data) return Find(T->right,x);
	else return T;
}
Bitree Findmin(Bitree T)//查找最小元素 
{
	if(T==NULL) return NULL;
	while(T->left)
	T=T->left;
	return T;
}
Bitree Findmin_s(Bitree T)//查找最小元素的递归
{
	if(T==NULL) return NULL;
	if(T->left==NULL) return T;
	else return Findmin_s(T->left);
}

插入和删除

Bitree Inserttree(Bitree &T,char x)//插入元素 (递归)
{
	if(T==NULL)
	{
		T=(Bitree)malloc(sizeof(BNode));
		T->data=x;
		T->left=T->right=NULL;
	}
	if(x<T->data)
	T->left=Inserttree(T->left,x);
	else if(x>T->data)
	T->right=Inserttree(T->right,x);
	return T;	
}
Bitree Inserttree_s(Bitree &T,char x)//插入元素 
{
	Bitree q=T,p=q;
	while(q)
	{
		if(x<q->data)
		{
			p=q;
			q=q->left;
		}
		else if(x>q->data)
		{
			p=q;
			q=q->right;
		}
		else return T;
	}
		Bitree P=(Bitree)malloc(sizeof(BNode));
		P->data=x;
		P->left=P->right=NULL;	
	if(p==NULL) T=P;
	else if(x<p->data) p->left=P;
	else if(x>p->data) p->right=P;
	return T;
}
Bitree Deletetree(Bitree &T,char x)//删除元素 
{
	if(T==NULL) return NULL;
	if(x<T->data) T->left=Deletetree(T->left,x);
	else if(x>T->data) T->right=Deletetree(T->right,x);
	else
	{
		if(T->left&&T->right)
		{
			Bitree t=Findmin(T->right);
			T->data=t->data;
			T->right=Deletetree(T->right,T->data);
					
		}
		else
		{
			Bitree temp=T;
			if(T->left==NULL) T=T->right;
			else if(T->right==NULL) T=T->left;
			free(temp);
		}	
	}
	return T;	
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值