//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);
}
}
04-树5 Root of AVL Tree
最新推荐文章于 2025-04-30 11:28:26 发布