数据结构-二叉排序树(建立、查找、修改)

二叉排序树概念

二叉排序树是动态查找表的一种,也是常用的表示方法。

其中,它具有如下性质:

1.若它的左子树非空,则其左子树的所有节点的关键值都小于根节点的关键值。

2.若它的右子树非空,则其右子树的所有节点的关键值都大于根结点的关键值。

3.它的左右子树也分别都是二叉排序树。

PS:对二叉排序树进行中序遍历,得到的序列,总会是一个升序的数列。

二叉排序树的建立

我们使用C语言来建立。

其中我们对二叉排序树的结构体定义如下:

cpp 复制代码
typedef int ElemType;
typedef struct BTNode{
    ElemType key;
    struct BTNode *lchild,*rchild;
}BTNode,*BSTree;

建立二叉排序树的代码如下:

cpp 复制代码
BSTree InsertBST(BSTree bst,BSTree s)		//遍历二叉排序树,找到合适的位置 
{
	if(bst==NULL)
		bst = s;
	else{
		if(s->key < bst->key)
			bst->lchild = InsertBST(bst->lchild,s);
		if(s->key > bst->key){
			bst->rchild = InsertBST(bst->rchild,s);
		}
	}
	return bst;
}

BSTree CreateBST()		//建立二叉排序树 
{
	BSTree bst,s;
	int key;
	bst = NULL;
	printf("请输入关键字值,输入-1结束.\n");
	while(1){
		scanf("%d",&key);
		if(key!=-1){
			s = (BSTree)malloc(sizeof(BTNode));
			s->key = key;
			s->lchild = NULL;
			s->rchild = NULL;
			bst = InsertBST(bst,s);
			printf("成功.\n");
		}
		else
			break;
	}
	return bst;
}

二叉排序树的插入

cpp 复制代码
BSTree InsertBST(BSTree bst,BSTree s)		//遍历二叉排序树,找到合适的位置 
{
	if(bst==NULL)
		bst = s;
	else{
		if(s->key < bst->key)
			bst->lchild = InsertBST(bst->lchild,s);
		if(s->key > bst->key){
			bst->rchild = InsertBST(bst->rchild,s);
		}
	}
	return bst;
}

BSTree SearchBST(BSTree bst,int key)		//查找关键值key的节点,并且返回这个节点 
{
	if(bst == NULL)
		return NULL;
	else if(key == bst->key)
		return bst;
	else if(key > bst->key)
		return SearchBST(bst->rchild,key);
	else
		return SearchBST(bst->lchild,key);
}

BSTree InsertBST_key(BSTree bst,int key)		//搜寻一个关键值,如果没有就插入 
{
	BSTree s;
	s = SearchBST(bst,key);
	if(s)
		printf("该节点已经存在.");
	else{
		s = (BSTree)malloc(sizeof(BTNode));
		s->key = key;
		s->lchild = NULL;
		s->rchild = NULL;
		s = InsertBST(bst,s);
	}
	return s;
}

查找二叉排序树指定节点的双亲

cpp 复制代码
BSTree SearchBST_F(BSTree bst,int key,BSTree *F)		//F存储key关键值节点的双亲节点,函数返回key关键值节点. 
{
	if(bst == NULL)
		return NULL;
	if(key == bst->key)
		return bst;
	else{
		*F = bst;
		if(key < bst->key)
			return SearchBST_F(bst->lchild,key,F);
		else
			return SearchBST_F(bst->rchild,key,F);
	}
}
相关推荐
多米Domi0112 小时前
0x3f 第49天 面向实习的八股背诵第六天 过了一遍JVM的知识点,看了相关视频讲解JVM内存,垃圾清理,买了plus,稍微看了点确定一下方向
jvm·数据结构·python·算法·leetcode
L_090711 小时前
【C++】高阶数据结构 -- 红黑树
数据结构·c++
划破黑暗的第一缕曙光15 小时前
[数据结构]:5.二叉树链式结构的实现1
数据结构
青桔柠薯片15 小时前
数据结构:单向链表,顺序栈和链式栈
数据结构·链表
XiaoFan01215 小时前
将有向工作流图转为结构树的实现
java·数据结构·决策树
睡一觉就好了。15 小时前
快速排序——霍尔排序,前后指针排序,非递归排序
数据结构·算法·排序算法
齐落山大勇15 小时前
数据结构——单链表
数据结构
皮皮哎哟16 小时前
深入浅出双向链表与Linux内核链表 附数组链表核心区别解析
c语言·数据结构·内核链表·双向链表·循环链表·数组和链表的区别
wWYy.17 小时前
指针与引用区别
数据结构
历程里程碑17 小时前
Linux 17 程序地址空间
linux·运维·服务器·开发语言·数据结构·笔记·排序算法