九、平衡二叉树
左旋转
右旋转
双旋转
上图直接右旋转,最后仍不然是平衡二叉树 双旋转的第一旋,目的就是把二叉树转换成"外侧"高度>"内侧"高度的标准格式,方便后续的旋转操作
package Tree.AVL;
public class demo {
public static void main(String[] args) {
int[] arr = {10, 11, 7, 6, 8, 9};
AVL avl = new AVL();
for (int item : arr) {
avl.add(new Node(item));
}
int height = avl.root.height();
System.out.println(height);
System.out.println(avl.root.leftHeight());
System.out.println(avl.root.rightHeight());
System.out.println(avl.root.value);
}
}
class AVL {
Node root;
public void add(Node node) {
if (root == null) {
root = node;
} else {
root.add(node);
}
}
public void infixOrder() {
if (root == null) {
System.out.println("二叉树为空,不能遍历");
return;
}
root.infixOrder();
}
}
class Node {
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
return "Node{" +
"value=" + value +
'}';
}
public void add(Node node) {
if (node == null) {
return;
}
if (node.value <= this.value) {
if (this.left == null) {
this.left = node;
} else {
this.left.add(node);
}
} else {
if (this.right == null) {
this.right = node;
} else {
this.right.add(node);
}
}
if (rightHeight() - leftHeight() > 1) {
if (right.leftHeight() > right.rightHeight()) {
right.rightRotate();
}
leftRotate();
} else if (leftHeight() - rightHeight() > 1) {
if (left.rightHeight() > left.leftHeight()) {
left.leftRotate();
}
rightRotate();
}
}
public void infixOrder() {
if (this.left != null) {
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null) {
this.right.infixOrder();
}
}
public int height() {
return Math.max(left == null ? 0 : left.height(), right == null ? 0 : right.height()) + 1;
}
public int leftHeight() {
if (left == null) {
return 0;
} else {
return left.height();
}
}
public int rightHeight() {
return right == null ? 0 : right.height();
}
public void leftRotate() {
Node newNode = new Node(value);
newNode.left = left;
if (right != null) {
newNode.right = right.left;
value = right.value;
left = newNode;
right = right.right;
}
}
public void rightRotate() {
Node newNode = new Node(value);
newNode.right = right;
if (left != null) {
newNode.left = left.right;
value = left.value;
right = newNode;
left = left.left;
}
}
}
|