一步一步复习数据结构和算法基础-二叉排序树

在二叉排序树中,大于根节点的数字是其右子树,小于根节点的数字是其左子树,等于根节点的情况,暂时不考虑。

操作:

插入、删除、遍历。

#include <stdio.h>
#include <stdlib.h>

typedef struct tree
{
	int data;
	struct tree *lchild,*rchild;
}BSTree,*ptree;

int SearchBST(ptree T,int key,ptree f,ptree *p)
{
	//如果是空树,返回空
	if(!T){(*p)=f;return 0;}
	else if(T->data == key){(*p)=T;return 1;}
	else if(T->data > key)return SearchBST(T->lchild,key,T,&(*p));
	else return SearchBST(T->rchild,key,T,&(*p));
}

int InsertBST(ptree *T,int key)
{
	ptree p,tmp;
	if(!SearchBST((*T),key,NULL,&p))
	{
		tmp = (ptree)malloc(sizeof(BSTree));
		tmp->data = key;tmp->lchild = tmp->rchild = NULL;
		//如果是空树那么当前节点是根节点
		if(!p)(*T) = tmp;
		//如果不是空树,那么p返回的是应该插入位置的父节点位置
		else if(p->data > key)p->lchild = tmp;
		else p->rchild = tmp;
		return 1;
	}
	return 0;
}

void InorderTree(ptree root)
{
	if(root)
	{
		InorderTree(root->lchild);
		printf("%d ",root->data);
		InorderTree(root->rchild);
	}
}

int Delete(ptree *node)
{
	ptree q,s;
	//没有右孩子
	if(!(*node)->rchild)
	{
		q = (*node);(*node) = (*node)->lchild;free(q);
	}
	//没有左孩子
	else if(!(*node)->lchild)
	{
		q = (*node);(*node) = (*node)->rchild;free(q);
	}
	//有两个孩子
	else
	{
		q=(*node);s=(*node)->lchild;
		//向右子树循环
		while(s->rchild){q=s;s=s->rchild;}
		//当前节点的数值替换(等效于删除)
		(*node)->data = s->data;
		if(q!=(*node))q->rchild=s->lchild;
		else q->lchild = s->lchild;
		free(s);
	}
	return 1;
}

//删除制定的数字
int DeleteBST(ptree *root,int key)
{
	//要想删除制定的数字需要先查找相应的数字
	if(!(*root))return 0;
	else
	{
		if((*root)->data == key)return Delete(root);
		else if((*root)->data > key)return DeleteBST(&(*root)->lchild,key);
		else return DeleteBST(&(*root)->rchild,key);
	}
}
int main()
{
	ptree root;
	int key,result;
	root = NULL;
	while(scanf("%d",&key) != EOF)
	{
		result = InsertBST(&root,key);
	}
	InorderTree(root);
	printf("\n");
	DeleteBST(&root,23);
	InorderTree(root);
	printf("\n");
	return 0;
}
//12 33 21 4 5 6 7 23 123 44




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值