博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
04-树5 Root of AVL Tree
阅读量:6241 次
发布时间:2019-06-22

本文共 2629 字,大约阅读时间需要 8 分钟。

04-树5 Root of AVL Tree(25 分)

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.

 

Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

Sample Input 1:

588 70 61 96 120

Sample Output 1:

70

Sample Input 2:

788 70 61 96 120 90 65

Sample Output 2:

88

#include 
#include
using namespace std;struct AVL{ int data; int height; struct AVL *left; struct AVL *right;};int getHeight(AVL *T){ if(T) return max(getHeight(T->left),getHeight(T->right))+1; else return 0;}AVL *LL(AVL *A){ AVL *B=new AVL; B=A->left; A->left=B->right; B->right=A; A->height=max(getHeight(A->left),getHeight(A->right))+1; B->height=max(getHeight(B->left),A->height)+1; return B;}AVL *RR(AVL *A){ AVL *B=new AVL; B=A->right; A->right=B->left; B->left=A; A->height=max(getHeight(A->left),getHeight(A->right))+1; B->height=max(A->height,getHeight(B->right))+1; return B;}AVL *LR(AVL *A){ A->left=RR(A->left); return LL(A);}AVL *RL(AVL *A){ A->right=LL(A->right); return RR(A);}AVL* Insert(int x,AVL *T){ if(!T){ T=new AVL; T->data=x; T->height=0; T->left=T->right=NULL; } else if(x
data){ T->left=Insert(x,T->left); if(getHeight(T->left)-getHeight(T->right)==2){ if(x
left->data) T=LL(T); else T=LR(T); } } else if(x>T->data){ T->right=Insert(x,T->right); if(getHeight(T->left)-getHeight(T->right)==-2){ if(x>T->right->data) T=RR(T); else T=RL(T); } } T->height=max(getHeight(T->left),getHeight(T->right))+1; return T;}void deleteTree(AVL *T){ if(T->left) deleteTree(T->left); if(T->right) deleteTree(T->right); delete T;}int main() { int n,num; AVL *T=NULL; cin>>n; for(int i=0;i
>num; T=Insert(num,T); } cout<
data<

转载于:https://www.cnblogs.com/JingwangLi/p/10202827.html

你可能感兴趣的文章
mybatis逆向工程之配置
查看>>
使用.NET 4.0+ 操作64位系统中的注册表
查看>>
剑指offer——面试题26:判断二叉树B是否为二叉树A的子结构
查看>>
scrapy主动退出爬虫的代码片段
查看>>
ny12 喷水装置(二)
查看>>
C\C++语言细节(2)
查看>>
Jenkins持续部署-自动生成版本号
查看>>
设计模式--代理模式
查看>>
javascript基础知识--最基础的
查看>>
[转] vue自定义组件(通过Vue.use()来使用)即install的使用
查看>>
[转] 函数声明和函数表达式——函数声明的声明提前
查看>>
敢死队2影评
查看>>
浅析 JavaScript 中的 apply 和 call 用法的差异
查看>>
html5-css综合练习
查看>>
嵌入式开发之cgic库---cgi库的使用
查看>>
clickhouse安装 Requires: libstdc++.so.6(GLIBCXX_3.4.19)(64bit)
查看>>
FFT快速傅立叶变换
查看>>
<刘未鹏 MIND HACKS>读书笔记
查看>>
locate
查看>>
AceyOffice教程--如何判断单元格的内容
查看>>