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.
PAT 甲级 1066 Root of AVL Tree (25 分)_第1张图片PAT 甲级 1066 Root of AVL Tree (25 分)_第2张图片
PAT 甲级 1066 Root of AVL Tree (25 分)_第3张图片
PAT 甲级 1066 Root of AVL Tree (25 分)_第4张图片

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:
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
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define inf 0x3f3f3f3f
typedef long long ll;
typedef pair<int,int> pa;
const int N = 1005;
#define min(a,b) a>b?a:b
struct node
{
    node *left,*right;
    int data;
};
node *root;
void SL(node * &root)  //左单旋(顺时针)
{
    node *tem=root;
    root=tem->left;
    tem->left=root->right;
    root->right=tem;
}
void SR(node * &root) //右单旋(逆时针)
{
    node *tem=root;
    root=tem->right;
    tem->right=root->left;
    root->left=tem;
}
void DLR(node * &root) //(左右双旋,左子树的右子树上插入导致的不平衡)
{
    SR(root->left);
    SL(root);
}
void DRL(node * &root)//(右左双旋,右子树的左子树上插入导致的不平衡)
{
    SL(root->right);
    SR(root);
}
int geth(node *root)
{
    if(root==NULL) return 0;
    int l=geth(root->left);
    int r=geth(root->right);
    return max(l,r)+1;
}
void insert(node * &root,int data)
{
    if(root==NULL)
    {
        root=new node;
        root->left=root->right=NULL;
        root->data=data;
        return;
    }

    if(data<root->data)
    {
        insert(root->left,data);
        if(geth(root->left)-geth(root->right)==2)
        {
            if(data<root->left->data)
                SL(root);
            else
                DLR(root);
        }
    }
    else
    {
        insert(root->right,data);
        if(geth(root->left)-geth(root->right)==-2)
        {
            if(data>root->right->data)
                SR(root);
            else
                DRL(root);
        }
    }
}
int main()
{
    root=NULL;
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        insert(root,x);
    }
    cout<<root->data<<endl;
    return 0;
}

你可能感兴趣的:(数据结构,PAT甲级)