AVL就是优化二叉查找树
平衡因子不大于1
左 < 根 < 右
具体看代码
#include<bits/stdc++.h> using namespace std; typedef struct node; typedef node * tree; struct node { int v; int heigh; tree L,R; }; //获取以root为根结点的子树的当前height int getheigh(tree root) { if(root==NULL) return 0; return root->heigh; } //更新结点root的heigh void updataheigh(tree root) { //max(左孩子结点的height,有孩子结点的height)+1 root->heigh=max(getheigh(root->L),getheigh(root->R))+1; } //计算平衡因子 int getBalance(tree root) { //左-右 return getheigh(root->L)-getheigh(root->R); } //左旋 注意原理 对于RR是root的右孩子的平衡因子是-1 void L(tree &root) { tree temp; temp=root->R; root->R=temp->L; temp->L=root; updataheigh(root); updataheigh(temp); root=temp; } void R(tree &root) { tree temp; temp=root->L; root->L=temp->R; temp->R=root; updataheigh(root); updataheigh(temp); root=temp; } void insertt(tree &root,int v) { if(root==NULL){//当结点是空的时候 就是插入的时候 root=new node; root->v=v; root->heigh=1; root->L=root->R=NULL; return; } if(v<root->v){ insertt(root->L,v); updataheigh(root);//注意更新树高 if(getBalance(root)==2){ if(getBalance(root->L)==1){ R(root); } else if(getBalance(root->L)==-1){ L(root->L); R(root); } } } else{ insertt(root->R,v); updataheigh(root); if(getBalance(root)==-2){ if(getBalance(root->R)==-1){ L(root); } else if(getBalance(root->R)==1){ R(root->R); L(root); } } } } int main() { int n; scanf(\"%d\",&n); int x; tree root; root=NULL; for(int i=0;i<n;i++){ scanf(\"%d\",&x); insertt(root,x); } printf(\"%d\\n\",root->v); return 0; }
继续阅读与本文标签相同的文章
上一篇 :
《环球时报》:“AI军备竞赛”,中国别掉以轻心
-
谷歌AI模型ML-Jam激发音乐家创作,人机合作或成未来大势!
2026-05-19栏目: 教程
-
OCP-052考试题库汇总(49)-CUUG内部解答版
2026-05-19栏目: 教程
-
自己实现 ECS 购买页需要用到的 API
2026-05-19栏目: 教程
-
Istio从懵圈到熟练 – 二分之一活的微服务
2026-05-19栏目: 教程
-
又一个里程碑,谷歌发布最新研究,机器学习开辟新篇章!
2026-05-19栏目: 教程
