栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【数据结构】浅谈二叉排序树

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构】浅谈二叉排序树

二叉排序树可以对一组数据进行查找、插入、删除操作。

简介

二叉排序树要么是空二叉树,要么具有如下特点:
如果其根结点有左子树,那么左子树上所有结点的值都小于根结点的值;
如果其根结点有右子树,那么右子树上所有结点的值都大小根结点的值;
二叉排序树的左右子树也要求都是二叉排序树。

简言之,二叉排序树的左子树、根节点、右子树中的数据依次递增!
1.左子树的数据比根结点数据小
2.右子树的数据比根结点数据大

实现过程

使用C++面向对象实现,使用二叉树的存储结构

结构体声明
struct BiNode{
	int data;
	BiNode *lchild;
	BiNode *rchild;
};
类的声明
class BiSortTree{
public:
	BiSortTree(int a[],int n);
	~BiSortTree(){Realese(root);}
	BiNode *Insert(int x){ return Insert(root, x);}
	BiNode *Search(int x){ return Search(root, x);}	

private:
	BiNode *root;
	BiNode *Insert(BiNode *bt,int x);
	BiNode *Search(BiNode *bt,int x);
	void Realese(BiNode * bt);		

};
插入函数

为保证二叉排序树的特征,在插入时,应先判断插入的位置:先与根比大小,之后递归调用插入函数将数据放入空位置!

BiNode *BiSortTree::Insert(BiNode *bt,int x){

	//插入元素插入到空位置 
	if(bt==NULL){			//找到空位置 
		BiNode *s=new BiNode;
		s->data=x;			//工作指针 
		bt=s;				 
		return bt;
	}
	
	//插入元素应先判断插入的位置:先与根比大小,之后递归调用插入函数 
	else if(x < bt->data) bt->lchild=Insert(bt->lchild,x);
	else if(x > bt->data) bt->rchild=Insert(bt->rchild,x);

}
构造函数

构造的就是不断插入结点的过程,构造函数要完成两件事:

  1. 根结点初始化;

  2. 不断调用插入函数,使得数据依次录入二叉排序树中。

BiSortTree::BiSortTree(int a[],int n){	//传入数据及其数目 
	//构造的就是不断插入结点的过程
	root=NULL;		//初始化根节点 
	int i;
	for(i=0;i 
查找函数 

查找过程类似二分查找,以根节点为基准,在合适区域查找指定元素

BiNode *BiSortTree::Search(BiNode *bt,int x){
	if(bt==NULL) return NULL;
	if(bt->data == x) return bt; 
	else if(x < bt->data) return Search(bt->lchild,x);
	else if(x > bt->data) return Search(bt->rchild,x); 
}
析构函数

二叉树本质上是二叉链表,属于动态存储,因此需手动析构。

void BiSortTree::Realese(BiNode * bt){
	if(bt==NULL) return ;
	else{
		Realese(bt->lchild);
		Realese(bt->rchild);
		delete bt;
	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/629587.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号