04-树5 Root of AVL Tree

来源:互联网 发布:sha256算法的基本流程 编辑:程序博客网 时间:2024/06/06 03:15

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 <iostream>#include<stack>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<T->data){        T->left=Insert(x,T->left);        if(getHeight(T->left)-getHeight(T->right)==2){            if(x<T->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<n;i++){        cin>>num;        T=Insert(num,T);    }    cout<<T->data<<endl;    deleteTree T;    return 0;}



原创粉丝点击