1. 程式人生 > >【PAT】1066. Root of AVL Tree (25)【平衡二叉樹的實現】

【PAT】1066. 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.
PAT1066題目圖片
Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

翻譯:一棵AVL樹為一棵平衡二叉搜尋樹。在一棵AVL樹中,兩個子樹直接的高度差最多為1。任何時候他們相差超過1,就會自動調整以恢復其特性。圖1-4說明了旋轉規則。
現在給你一組插入數列,你需要說出結果AVL樹的根節點。

INPUT FORMAT

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.

翻譯:每個輸入檔案包含一組測試資料。對於每組輸入資料,第一行包括一個正整數N(<=20),代表插入的鍵值總數。接著下一行給出N個不重複的整數鍵值。所有數字之間用空格隔開。

OUTPUT FORMAT

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

翻譯:對於每組輸入資料,輸出一行AVL樹的根節點。

Sample Input 1:

5
88 70 61 96 120

Sample Output 1:

70

Sample Input 2:

7
88 70 61 96 120 90 65

Sample Output 2:

88

解題思路

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#define INF 99999999
using namespace std;
struct Node{
    int data,height;
    Node *lc,*rc;
    Node(){}
    Node(int a):data(a),height(0),lc(NULL),rc(NULL){} 
};
int getHeight(Node* &a){
    if(a==NULL)return -1;
    else return a->height;
}
void LL(Node* &root){
    Node *a=root->lc;
    root->lc=a->rc;
    a->rc=root;
    a->height=max(getHeight(a->lc),getHeight(a->rc))+1;
    root->height=max(getHeight(root->lc),getHeight(root->rc))+1;
    root=a;
}
void RR(Node* &root){
    Node *a=root->rc;
    root->rc=a->lc;
    a->lc=root;
    a->height=max(getHeight(a->lc),getHeight(a->rc))+1;
    root->height=max(getHeight(root->lc),getHeight(root->rc))+1;
    root=a;
}
void LR(Node* &root){
    RR(root->lc);
    LL(root);
} 
void RL(Node* &root){
    LL(root->rc);
    RR(root);
} 
void insert(Node* &root,int val){
    if(root==NULL){
        root=new Node(val);
        return ;
    }
    if(val<root->data){
        insert(root->lc,val);
        if(getHeight(root->lc)-getHeight(root->rc)>1){
            if(val<root->lc->data)LL(root);
            else LR(root);
        }
    }
    if(val>=root->data){
        insert(root->rc,val);
        if(getHeight(root->rc)-getHeight(root->lc)>1){
            if(val>root->rc->data)RR(root);
            else RL(root);
        }
    }
    root->height=max(getHeight(root->lc),getHeight(root->rc))+1;
}
int N;
int main(){
    scanf("%d",&N);
    Node *root=NULL;
    int a;
    for(int i=0;i<N;i++){
        scanf("%d",&a);
        insert(root,a);
    }
    printf("%d\n",root->data);
    return 0;
}