数据结构中平衡二叉树的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);

本文提供了一种使用C++实现AVL树的方法,包括插入、删除和查找等基本操作,并通过测试验证了其实现的有效性和正确性。
&spm=1001.2101.3001.5002&articleId=111570474&d=1&t=3&u=fdda8ebdfeae4ec3bd1b87d623e5a1e2)
2039

被折叠的 条评论
为什么被折叠?



