package org.structure.avlTree;
/**
* 种一棵二叉平衡树(Avl树)
* @author cjj_1
* @date 2020-09-02 13:46
*/
public class AvlTreeDemo {
public static void main(String[] args) {
// int[] arr ={4,3,6,5,7,8};
int[] arr={10,7,11,6,8,9};
AvlTree tree = new AvlTree();
for(int i:arr){
tree.add(new Node(i));
}
System.out.println(tree.root);
tree.root.infixOrder();
}
}
class AvlTree{
Node root;
public void add(Node node) {
if (root == null) {
root = node;
} else {
root.add(node);
}
}
}
class Node{
Integer 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 (this.value > node.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(left!=null && right!=null && left.getHight()-right.getHight()>1){
if(left.right.getHight()>left.left.getHight()){
//左子树左旋转
left.leftRotate();
}
//向右旋转
rightRotate();
}
if(left!=null && right!=null && right.getHight()-left.getHight()>1){
if(right.left.getHight() > right.right.getHight()){//如果右子树的左子树高度》右子树的右子树
//右子树右旋转
right.rightRotate();
}
leftRotate();
}
}
/**
* 向左旋转
*/
public void leftRotate(){
Node newNode = new Node(value);
newNode.left = left;
newNode.right = right.left;
value = right.value;
left = newNode;
right = right.right;
}
/**
* 向右旋转
*/
public void rightRotate(){
Node newNode = new Node(value);
newNode.right = right;
newNode.left = left.right;
value = left.value;
left = left.left;
right = newNode;
}
/**
* 当前节点为根节点的高度
* @return
*/
public int getHight(){
return Math.max(left == null?0:left.getHight(),right ==null?0:right.getHight())+1;
}
/**
* 中序遍历
*/
public void infixOrder(){
if(this.value == null){
return;
}
if(this.left!=null){
this.left.infixOrder();
}
System.out.println(this.value);
if(this.right!=null){
this.right.infixOrder();
}
}
}
种二叉平衡树,二叉平衡树的左旋转,右旋转
最新推荐文章于 2024-07-16 16:37:19 发布