PAT甲级1066 Root of AVL Tree (25分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

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:

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

二、解题思路

这道题是一道比较完整的AVL树的题目,基本涉及到了AVL树的所有操作,很适合学完AVL树之后用来巩固。具体的知识可以参考《算法笔记》中关于AVL树的讲解。

三、AC代码

#include<iostream>
#include<algorithm>
using namespace std;
struct Node //建立结点结构体
{
    
    
    int key;
    Node* lchild, *rchild;
};
Node* rotateLeft(Node* root)    //左旋操作
{
    
    
    Node *t = root->rchild;
    root->rchild = t->lchild;
    t->lchild = root;
    return t;
}
Node* rotateRight(Node* root)   //右旋操作
{
    
    
    Node *t = root->lchild;
    root->lchild = t->rchild;
    t->rchild = root;
    return t;
}
Node* rotateLeftRight(Node* root)   //先左旋再右旋
{
    
    
    root->lchild = rotateLeft(root->lchild);
    return rotateRight(root);
}
Node* rotateRightLeft(Node* root)   //先右旋再左旋
{
    
    
    root->rchild = rotateRight(root->rchild);
    return rotateLeft(root);
}
int getHeight(Node* root)   //获取高度
{
    
    
    if(root == NULL)    return 0;
    return max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
Node* insert(Node *root, int val)   //AVL树的插入
{
    
    
    if(root == NULL)
    {
    
    
        root = new Node();
        root->lchild = NULL;
        root->rchild = NULL;
        root->key = val;
        return root;
    }
    else if(val < root->key)
    {
    
    
        root->lchild = insert(root->lchild, val);
        if(getHeight(root->lchild) - getHeight(root->rchild) == 2)
            root = val < root->lchild->key ? rotateRight(root) : rotateLeftRight(root);
    }
    else
    {
    
    
        root->rchild = insert(root->rchild, val);
        if(getHeight(root->rchild) - getHeight(root->lchild) == 2)
            root = val > root->rchild->key ? rotateLeft(root) : rotateRightLeft(root);
    }
    return root;
}
int main()
{
    
    
    int N, val;
    scanf("%d", &N);
    Node *root = NULL;
    for(int i=0; i<N; i++)
    {
    
    
        scanf("%d", &val);
        root = insert(root, val);
    }
    printf("%d", root->key);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108704953