04-树4. Root of AVL Tree (25)

来源:互联网 发布:网络摄像机说明书 编辑:程序博客网 时间:2024/06/11 14:38

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 ythe 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

提交代码

--------------------------------------

记不住旋转,怎么办,就按照讲解的一点一点的抠出来了。

pat不会考这个如何旋转吧。。。。

上一篇已经转载了一位同志的讲解。

本题主要是每读入一个数据,将其插入进来,如果不AVL 的话,进行调整。

如果能记住怎么旋转的,就比较好写了。

代码如下。

-----------------------------------------

#include <iostream>#include <stdlib.h>using namespace std;/* run this program using the console pauser or add your own getch, system("pause") or input loop */typedef struct AVLTree{int data;AVLTree *l;AVLTree *r;int height;AVLTree(int data):data(data),l(NULL),r(NULL),height(0){};}*pAVLTree;int getheight(pAVLTree p){if(p==NULL) return 0;return p->height;}bool isBalanced(pAVLTree p){return abs(getheight(p->l) - getheight(p->r))<2;}pAVLTree LL(pAVLTree p){pAVLTree child = p->l;p->l=child->r;child->r=p;p->height=max(getheight(p->l), getheight(p->r))+1;child->height=max(getheight(child->l), p->height)+1;return child;}pAVLTree RR(pAVLTree p){pAVLTree child = p->r;p->r=child->l;child->l=p;p->height=max(getheight(p->l), getheight(p->r))+1;child->height=max(getheight(child->r), p->height)+1;return child;}pAVLTree LR(pAVLTree p){pAVLTree child=p->l;p->l=RR(child);return LL(p);}pAVLTree RL(pAVLTree p){pAVLTree child=p->r;p->r=LL(child);return RR(p);}pAVLTree insertion(pAVLTree pt, int v)//insert a value{if(pt==NULL){pt=(pAVLTree)malloc(sizeof(struct AVLTree));pt->l=pt->r=NULL;pt->data=v;pt->height=0;}else if(v<pt->data)//l{pt->l=insertion(pt->l,v);if(!isBalanced(pt)){if(v>pt->l->data)//LR{pt=LR(pt);}else//LL{pt=LL(pt);}}}else if(v>pt->data)//R{pt->r=insertion(pt->r,v);if(!isBalanced(pt)){if(v>pt->r->data)//RR{pt=RR(pt);}else//RL{pt=RL(pt);}}}pt->height=max(getheight(pt->l), getheight(pt->r))+1;return pt;}int main(int argc, char** argv) {int N=0,tmp=0;int a[21];pAVLTree root=(pAVLTree)malloc(sizeof(struct AVLTree));root=NULL;cin>>N;for(int i=0; i<N; i++){cin>>tmp;root=insertion(root,tmp);}cout<<root->data<<endl;return 0;}


工程文件。。。

http://download.csdn.net/detail/xkzju2010/8766875

0 0
原创粉丝点击