AVL(平衡)树

P3374-数据结构实验之查找二:平衡二叉树

Time Limit: 400MS Memory Limit: 65536KB

Problem Description

根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。

Input

输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。

Output

输出平衡二叉树的树根。

Example Input

5
88 70 61 96 120

Example Output

70

Hint

 

Author

xam
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <map>
#include <stack>
#include <queue>
using namespace std;
int i,n;
struct node
{
    int data,height;
    node*left,*right;
    node(){left=NULL;right=NULL;height=1;}
};
int geth(node*root) //获得高度,防止访问无效内存
{
    if(!root) return 0;
    else return root->height;
}
int balance(node*root) //获得平衡常数
{
    return geth(root->left)-geth(root->right);
}
void LL(node*&root)  //LL型
{
    node*p = root->left;
    root->left = p->right;
    p->right = root;
    root->height = max(geth(root->left),geth(root->right))+1; //更新高度
    root = p;

}
void RR(node*&root)
{
    node*p = root->right;
    root->right = p->left;
    p->left = root;
    root->height = max(geth(root->left),geth(root->right))+1;
    root = p;
}
void LR(node*&root)
{
    RR(root->left);
    LL(root);
}
void RL(node*&root)
{
    LL(root->right);
    RR(root);
}
void add(node*&root,node*p)
{
    if(!root)
    {
        root = p;
        return;
    }
    if(root->data>p->data)
    {
        add(root->left,p);
        if(balance(root)==2)
        {
            if(balance(root->left)==1)
                LL(root);
            else LR(root);
        }
    }
    else
    {
        add(root->right,p);
        if(balance(root)==-2)
        {
            if(balance(root->right)==-1)
                RR(root);
            else RL(root);
        }

    }
    root->height = max(geth(root->left),geth(root->right))+1;
}
int main()
{
    //freopen("a.txt","r",stdin);
    ios::sync_with_stdio(0);
    cin>>n;
    node *root;
    root = NULL;
    for(i = 1;i <= n;i ++)
    {
        node*p;
        p = new node;
        cin>>p->data;
        add(root,p);
    }
    cout<<root->data;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_30358129/article/details/79154883