4.2 Exercise balanced binary tree root (25 points)

Given a series of numbers inserted initially empty AVL tree, the root of your output value last generation AVL tree.

Input formats:

The first line of the input is given a positive integer N ( ≦ 20), followed by a line gives N different integers, separated by a space therebetween.

Output formats:

After a row is inserted in the output order of the integer into an initially empty AVL tree, the value of the root of the tree.

Sample Input 1:

5
88 70 61 96 120
 

Output Sample 1:

70
 

Sample Input 2:

7
88 70 61 96 120 90 65 
 

Output Sample 2:

88

Adjustment generating binary sort tree is a balanced binary tree simultaneously: solving ideas
case need to be adjusted:
1, left single spin

 

2, the right rotation only

 

 

 3, after the first right-handed left-handed

 

 

 4, after the first left-handed right-handed

 

 

 

#include <stdio.h>
#include <malloc.h>
#define ElemType int
typedef struct BiTNode {
    ElemType Data;
    struct BiTNode *Left;
    struct BiTNode *Right;
}*AVLTree;
AVLTree SingleLeftRotation(AVLTree T) {//左单旋
    AVLTree B=T->Left;
    T->Left=B->Right;
    B->Right=T;
    return B;
}
AVLTree SingleRightRotation(AVLTree T) {//右单旋
    AVLTree B=T->Right;
    T-> = the B-Right> Left; 
    B -> Left = T;
     return B; 
} 
AVLTree DoubleLeftRightRotation (AVLTree T) {// about an ambidextrous 
    T -> Left = SingleRightRotation (T-> Left);
     return SingleLeftRotation (T) ; 
} 
AVLTree DoubleRightLeftRotation (AVLTree T) {// ambidextrous left and right 
    T -> = Right SingleLeftRotation (T-> Right);
     return SingleRightRotation (T); 
} 

AVLTree the Insert (AVLTree T, X-elemType) { 
    IF (! T) { 
        T = (AVLTree) the malloc ( the sizeof (AVLTree)); // every time a new node is inserted into the space to apply for 
        T->Data=X;
        T->Left=NULL;
        T->Right=NULL;
    } else {
        if(X>T->Data) {//往右子树找位置
            T->Right=Insert(T->Right,X);
            if(GetHeight(T->Right)-GetHeight(T->Left)==2) {
                if(X<T->Right->Data) {
                    T=DoubleRightLeftRotation(T);
                } else T=SingleRightRotation(T);
            }
        } else if(X<T->Data) {//往左子树找位置
            T->Left=Insert(T->Left,X);
            if(GetHeight(T->Left)-GetHeight(T->Right)==2) {
                if(X>T->Left->Data) {
                    T=DoubleLeftRightRotation(T);
                } else T=SingleLeftRotation(T);
            }
        }
    }
    return T;

}
int GetHeight(AVLTree T) {//求树高
    if(!T)
        return 0;
    int hl=GetHeight(T->Left);
    int hr=GetHeight(T->Right);
    return (hl>hr?hl:hr)+1;
}
int main() {
    int n,x,i;
    scanf("%d",&n);
    AVLTree T=NULL;//初始化为NULL;
    for(i=0; i<n; i++) {
        scanf("%d",&x);
        T=Insert(T,x);
    }
    printf("%d",T->Data);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/snzhong/p/12416429.html