数据结构-平衡二叉树(C++代码实现)

本文提供了一种使用C++实现AVL树的方法,包括插入、删除和查找等基本操作,并通过测试验证了其实现的有效性和正确性。

数据结构中平衡二叉树的C++代码实现

有关参考博客:https://blog.csdn.net/qq_25940921/article/details/82183093
https://www.cnblogs.com/zhangbaochong/p/5164994.html

代码及其测试结果如下

Code :

/*
二叉平衡搜索树(AVL):对于二叉搜索树的所有结点,其左右节点的高度之差不超过 1 
*/ 
#include<iostream>
#include<queue>
using namespace std;
typedef int KeyType;
typedef int ElemType;
typedef struct BSTNode{
   
   
	KeyType key;
	int height;
	ElemType data;
	BSTNode *left,*right;
	BSTNode()=default;
	BSTNode(KeyType k):key(k),height(1),data(0),left(NULL),right(NULL){
   
   }
}BSTree;

int GetHeight(BSTree *rt){
   
   	//得到高度 
	if(rt==NULL)	return 0;
	return rt->height;
}

void UpdateHeight(BSTree *rt){
   
   	//更新高度 
	if(rt==NULL)	return;
	rt->height=max(GetHeight(rt->left),GetHeight(rt->right))+1;
}

//左左调整(bf=2),右旋,左子节点变成父节点,其多余的右子节点变成降级节点的左子节点 
void UpdateLL(BSTree *&rt){
   
   
	BSTree *pl=rt->left;
	rt->left=pl->right;
	pl->right=rt;
	rt=pl;
	UpdateHeight(rt->left);
	UpdateHeight(rt->right);
	UpdateHeight(rt);
}

//右右调整(bf=-2),左旋,右子节点变成父节点,其多余的左子节点变成降级节点的右子节点 
void UpdateRR(BSTree *&rt){
   
   
	BSTree *pr=rt->right;
	rt->right=pr->left;
	pr->left=rt;
	rt=pr;
	UpdateHeight(rt->left);
	UpdateHeight(rt->right);
	UpdateHeight(rt);
}

//左右调整(bf=2),先对左子节点左旋调整为左左型,再进行左左调整 
void UpdateLR(BSTree *&rt){
   
   
	UpdateRR(rt->left);
	UpdateHeight(rt->left->left);
	UpdateHeight(rt->left->right);
	
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值