[JavaSE] data structure (Basic AVL Tree concept), javaseavl
The AVL Tree is a highly balanced binary tree. The height difference between the two Subtrees on any node <= 1
Implement AVL Tree
Define an AVL Tree, AVLTree, and AVLNode, which has the following features:
1. key -- Keyword: sorts nodes in the AVL Tree.
2. left -- left subtree
3. right -- right subtree
4. height -- height
If a node is inserted into the AVL Tree, the AVL tree may be out of balance. There are four statuses:
LL: Left left, LeftLeft
LR: Left and Right, LeftRight
RL: Right left, RightLeft
RR: Right right, RightRight
Solve the problem above
Solve LL, which requires a single left Rotation
Solve RR, right single rotation required
To solve the LR problem, you must first rotate the right one and then rotate the right one.
To solve RL, you must first rotate the left and then rotate the right
Achieve left single rotation
K1, k2
Left of k2 to k1
Right of k1 to left of k2
K2 gives k1 the right
Achieve right single rotation
K1, k2
K1 right to k2
Left of k2 to right of k1
Left of k1 to k2
The height of a node is the one in the left or right subtree.
/*** AVL Tree test * @ author taoshihan * @ param <T> **/public class AVLTree <T extends Comparable <T> {private AVLNode mRoot; // root node class AVLNode <T extends Comparable <T> {private T key; // key value private int height; // height private AVLNode left; // left subtree private AVLNode right; // right subtree public AVLNode (T key, AVLNode left, AVLNode right) {this. key = key; this. left = left; this. right = right; this. height = 0 ;}/ *** get node height * @ par Am tree * @ return */public int height (AVLNode <T> tree) {if (tree! = Null) {return tree. height;} return 0;}/*** retrieve the * @ param a * @ param B * @ return */public int maxHeight (int, int B) {return a> B? A: B;}/*** left single rotation * @ param k2 * @ return */public AVLNode <T> leftLeftRotation (AVLNode <T> k2) {AVLNode k1; k1 = k2.left; k2.left = k1.right; k1.right = k2; k2.height = maxHeight (height (k2.left), height (k2.right); k1.height = maxHeight (height (k1.left ), height (k1.right); return k1;}/*** right single rotation * @ param k2 * @ return */public AVLNode <T> rightRightRotation (AVLNode <T> k1) {AVLNode k2; k2 = k1.right; k1.right = k2.left; k2.left = k1; k2.height = maxHeight (k2.left), height (k2.right); k1.height = maxHeight (height (k1.left ), height (k1.right); return k2 ;}