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

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

简介

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

简言之,二叉排序树的左子树、根节点、右子树中的数据依次递增!
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<n;i++){
		root=Insert(root,a[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;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值