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.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer NNN (≤20\le 20≤20) which is the total number of keys to be inserted. Then NNN 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平衡搜索树二叉树.
import java.util.Scanner; class Node{ Node left,right; int data; int height; public Node(int data){ this.data = data; this.left = null; this.right = null; this.height = 0; } } class AVLTree{ //RR旋转 private Node RR(Node root){ Node newroot = root.right; root.right = newroot.left; newroot.left = root; root.height = setHeight(root); newroot.height = setHeight(newroot); return newroot; } //LL旋转 private Node LL(Node root){ Node newroot = root.left; root.left = newroot.right; newroot.right = root; root.height = setHeight(root); newroot.height = setHeight(newroot); return newroot; } //RL旋转 private Node RL(Node root){ root.right = LL(root.right); return RR(root); } //LR旋转 private Node LR(Node root){ root.left = RR(root.left); return LL(root); } //设置height private int setHeight(Node root){ if(root==null){ return 0; } return 1+Math.max((root.left!=null?root.left.height:0),(root.right!=null?root.right.height:0)); } //获取height private int getHeight(Node root){ if(root==null){ return 0; } return root.height; } //获得平衡因子 private int balance(Node root){ return getHeight(root.left)-getHeight(root.right); } //插入节点 public Node insert(Node root,int data){ if(root==null){ root = new Node(data); }else if(data>=root.data){ root.right = insert(root.right,data); //需要进行R旋转 if(balance(root)<-1){ if(getHeight(root.right.right)>getHeight(root.right.left)){//需要进行RR旋转 root = RR(root); }else if(getHeight(root.right.right)<getHeight(root.right.left)){//需要进行RL旋转 root = RL(root); } } }else if(data<root.data){ root.left = insert(root.left,data); //需要进行L旋转 if(balance(root)>1){ if(getHeight(root.left.left)>getHeight(root.left.right)){//需要进行LL旋转 root = LL(root); }else if(getHeight(root.left.left)<getHeight(root.left.right)){//需要进行LR旋转 root = LR(root); } } } root.height = setHeight(root); return root; } } public class Main{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); AVLTree avl = new AVLTree(); Node root = null; while(T--!=0){ int num = scan.nextInt(); root = avl.insert(root,num); } System.out.println(root.data); } }