04-树5 Root of AVL Tree

//04-树5 Root of AVL Tree

import java.util.Scanner;

class Tnode{
    int data = 0;
    Tnode left;
    Tnode right;
    int h;
}

public class Main{
    static int Max(int a, int b){
        return a > b ? a : b;
    }

    static int GetH(Tnode T){
        int h;
        if(T == null){
            h = 0;
        }
        else{
            h = T.h;
        }
        return h;
    }

    static Tnode RR(Tnode A){
        Tnode B = A.right;
        A.right = B.left;
        B.left = A;
        A.h = Max(GetH(A.left), GetH(A.right)) + 1;
        B.h = Max(GetH(B.left), GetH(B.right)) + 1;
        return B;
    }

    static Tnode LL(Tnode A){
        Tnode B = A.left;
        A.left = B.right;
        B.right = A;
        A.h = Max(GetH(A.left), GetH(A.right)) + 1;
        B.h = Max(GetH(B.left), GetH(B.right)) + 1;
        return B;
    }

    static Tnode LR(Tnode A){
        A.left = RR(A.left);
        return  LL(A);
    }

    static Tnode RL(Tnode A){
        A.right = LL(A.right);
        return RR(A);
    }

    static Tnode insert(Tnode R, int a){
        if(R == null){
            Tnode T = new Tnode();
            T.data = a;
            T.h = 0;
            T.left = null;
            T.right = null;
            R = T;
        }
        else{
            if(a > R.data){
                R.right = insert(R.right, a);
                if(GetH(R.left) - GetH(R.right) == -2){
                    if(a > R.right.data){
                        R = RR(R);
                    }
                    else{
                        R = RL(R);
                    }
                   }

            }
            else if(a < R.data){
                R.left = insert(R.left, a);
                if(GetH(R.left) - GetH(R.right) == 2){
                    if(a < R.left.data){
                        R = LL(R);
                    }
                    else{
                        R = LR(R);
                    }
                }
            }
        }
        R.h = Max(GetH(R.left), GetH(R.right)) + 1;
        return R;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();
        int a = 0;
        Tnode R = null;
        for(int i = 0; i < N; i ++){
            a = s.nextInt();
            R = insert(R, a);
        }
        System.out.println(R.data);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值