(c语言详解)04-树5 Root of AVL Tree(详细解释)

本实验源于浙江大学《数据结构》,这道题主要源于AVL树,因此对AVL树的理解十分关键。
AVL细致讲解链接
然后看完之后,自己在main函数里将输入的场景模拟好,最后打印根节点,也就是本身AVL树的value就可以出答案,打完收工提交解决。

#include<stdio.h>
#include <stdlib.h>


typedef struct AVLNode* AVLTree ;

struct AVLNode{
    int val;
    AVLTree left;
    AVLTree right;
    int height; 
}; 

//求数的深度的函数 
int max(int a,int b)
{
	return a>b?a:b;
}
int getHeight(AVLTree t) 
{  
    if (t)  
        return max(getHeight(t->left) , getHeight(t->right)) + 1;  
    else  
        return 0;  
}  

//左旋 
AVLTree SingleLeftRotation(AVLTree a) 
{   
    AVLTree 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;  
}  

//右旋 
AVLTree SingleRightRotation(AVLTree t) 
{  
    AVLTree b = t->right;  
    t->right = b->left;  
    b->left = t;  
    t->height = max(getHeight(t->left), getHeight(t->right)) + 1;  
    b->height = max(getHeight(b->right),t->height) + 1;  
    return b;  
}  

//左右旋 
AVLTree DoubleLeftRightRotation(AVLTree t) 
{  
    t->left = SingleRightRotation(t->left);  
    return SingleLeftRotation(t);  
}  

//右左旋 
AVLTree DoubleRightLeftRotation(AVLTree t) 
{  
    t->right = SingleLeftRotation(t->right);  
    return SingleRightRotation(t);  
}  

//插入函数 
AVLTree AVL_Insertion(int x, AVLTree t)
{
    /* 插入X到AVL中 并返回调整后的AVL树 */  
    if (!t) {  
        t = (AVLTree)malloc(sizeof(struct AVLNode));  
        t->val = x;  
        t->height = 0;  
        t->left = t->right = NULL;  
    }  
    else if (x < t->val) {  
        t->left = AVL_Insertion(x, t->left);  
        if (getHeight(t->left) - getHeight(t->right) == 2) {  
            /*需要左旋*/  
            if (x < t->left->val) {  
                t = SingleLeftRotation(t);/* 左单旋 */  
            }  
            else {  
                t = DoubleLeftRightRotation(t); /* 左右双旋 */  
            }  
        }  
    }  
    else if ( x> t->val) {  
        t->right = AVL_Insertion(x, t->right);  
        if (getHeight(t->right) - getHeight(t->left) == 2) {  
            /*需要左旋*/  
            if (x > t->right->val) {  
                t = SingleRightRotation(t);/* 左单旋 */  
            }  
            else {  
                t = DoubleRightLeftRotation(t); /* 右左双旋 */  
            }  
        }  
    }  
    t->height = max(getHeight(t->left), getHeight(t->right)) + 1;  
    return t;  
 } 

int main()
{
    int N;
    //cin>>N;
    scanf("%d",&N);
	AVLTree avl = NULL;
    for ( int i = 0 ; i < N ; i++){
        int t;
        //cin>>t;
        scanf("%d",&t);
		avl = AVL_Insertion(t,avl);
    }

    //cout<<avl->val; 
    printf("%d",avl->val);
	return 0;
}
发布了137 篇原创文章 · 获赞 30 · 访问量 8853

猜你喜欢

转载自blog.csdn.net/m0_37149062/article/details/105470471