二叉搜索树的查找,删除,插入-C语言代码

1. 什么是二叉搜索树?

在这里插入图片描述

2. 基本操作

2.1 存储结构
#include <stdio.h>
#include<stdlib.h> 
#define ElementType int 
typedef  struct TreeNode
{
	ElementType data;
	TreeNode* lchild;
	TreeNode* rchild;
}BinSearchTree;
2.2 建树(前序遍历建树)
void CreateTree(BinSearchTree** root)//前序遍历
{
	ElementType ch;
	scanf("%d\n",&ch);
	//ch=getchar();
	if (ch==-1){
		
		*root=NULL;
	}	
	else{
		
			(*root)=(BinSearchTree*)malloc(sizeof(TreeNode));
			(*root)->data=ch;
			CreateTree(&((*root)->lchild));
			CreateTree(&((*root)->rchild));                               	
	}	
}
2.3 查找某个元素(迭代查找,非递归)
BinSearchTree* IterFind(BinSearchTree* root,ElementType x)
{
	while(root){
		if(x>root->data){
			root=root->rchild;
		}
		else if(x<root->data){
			root=root->lchild;
		}
		else{
			return root;
		}
	}
	return NULL;
}
2.4 查找最大元素

最右边的元素是最大的

BinSearchTree* FindMax(BinSearchTree* root)
{
	while(root->rchild){
		root=root->rchild;
		
	}
	return root;
}
2.5 查找最小元素

最右边的元素是最小的

BinSearchTree* FindMin (BinSearchTree* root)
{
	while(root->lchild){
		root=root->lchild;
		
	}
	return root;
}
2.6 插入一个元素
BinSearchTree* Insert(BinSearchTree* root,int x)
{
	if(!root){
		root=(BinSearchTree*)malloc(sizeof(TreeNode));
		root->data=x;
		root->lchild=root->rchild=NULL;
	}
	else 
		if(x>root->data){
			root->rchild=Insert(root->rchild,x);
		}else if(x<root->data){
			root->lchild=Insert(root->lchild,x);
		}
	return root;
}
2.7 删除一个元素
BinSearchTree* Delete(BinSearchTree* root,int x)
{
	BinSearchTree* tmp;
	if(!root){
		printf("未找到!");
	}
	else{
		if(x>root->data){
			root->rchild=Delete(root->rchild,x);
		}else if(x<root->data){
			root->lchild=Delete(root->lchild,x);
		}else{
			if(root->lchild && root->rchild){
				tmp=FindMin(root->rchild);
				root->data=tmp->data;
				
				root->rchild=Delete(root->rchild,root->data);
			}else{
				tmp=root;
				if(!root->lchild){
					root=root->rchild;
				}
				else{
					root=root->lchild;
				}
				free(tmp);
			}
		}
	}
	return root;
}
2.8 输出树
void PrintTree(BinSearchTree* root,int h)
{
	if(root==NULL)	return;
	else{
		PrintTree(root->rchild,h+1);
		for(int i=0;i<h;i++)	printf("\t");
		printf("%d\n",root->data);
		PrintTree(root->lchild,h+1);
	}
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值