平衡二叉树AVL

What
平衡二叉树AVL:平衡二叉树也叫平衡二叉搜索树(Self-balancing binary search tree),又被称为AVL树, 可以保证查询效率较高。它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。平衡二叉树的常用实现方法有红黑树、AVL、替罪羊树、Treap、伸展树等

如图1中的第一棵树和第二棵树都是平衡二叉树,第三棵不是平衡二叉树

18722707-08f57babe9666195.png
图1
Why
可能会有这样一种情况:将 [1 , 12 , 23 , 34 , 45 , 56] 这个数列(即已经有序的数列)构建成一棵BST,如图2
18722707-01910949b3a60f21.png
图2
对于这棵二叉排序树,存在着一些问题:
  • 左子树全部为空,看着就像一条链表
  • 插入速度与BST一样,没有受到影响;但是查询速度明显降低,因为需要依次进行比较,时间复杂度从O(lgn)变成了O(n),另外每次还需要比较左子树(实际左子树又不存在,会浪费时间)
对于上面的问题,解决方案就是平衡二叉树(AVL)
HOW
1.在开始写代码之前需要先理解二叉树的左旋转、右旋转、双旋转是什么?

在构建平衡二叉树过程中,当某个节点的左右子树的高度差的绝对值大于1时,此时的二叉树就不在是一颗AVL树,这时可以通过左旋、右旋或者双旋转将它调整成一颗AVL树

1.1 左旋

18722707-8b3471441d0c8f46.gif
图3.左旋转动画
18722707-744f2c3f1a9dfaa5.png
图4

将数列[4 , 3 , 6 , 5 , 7 , 8]构建成AVL树(构建过程和BST一样,不过添加时需要判断左右子树的高度差,不满足AVL定义时进行调整操作);如图4,当插入8时,根节点的左子树与右子树的高度差绝对值为2,此时不满足AVL树的定义,需要对根节点为4的树进行左旋操作。

参考图4,左旋过程如下:

  • 第1步:创建一个新节点newNode(红色),新节点的值为当前被左旋的树的根节点
  • 第2步:把newNode的左子树设置为根节点的左子树
  • 第3步:把newNode的右子树设置成根节点的右子树的左子树
  • 第4步:把根节点的值替换成根节点的右子节点的值
  • 第5步:把根节点的右子树设置成右子树的右子树
  • 第6步:把根节点的左子树设置成newNode
  • 最后,原来的值为6的节点(灰色)会被垃圾回收回收掉

1.2 右旋

18722707-997d913e7e28c43d.gif
图5.右旋转动画
18722707-5138cd59e0d141ad.png
图6

将数列[10 , 12 , 8 , 9 , 7 ,6]构建成AVL树;如图6,当插入6时,根节点的左子树与右子树的高度差绝对值为2,此时不满足AVL树的定义,需要对根节点为10的树进行右旋操作。

参考图6,左旋过程如下:

  • 第1步:创建一个新节点newNode(红色),新节点的值为当前被右旋的树的根节点
  • 第2步:把newNode的右子树设置为根节点的右子树
  • 第3步:把newNode的左子树设置成根节点的左子树的右子树
  • 第4步:把根节点的值替换成根节点的左子节点的值
  • 第5步:把根节点的左子树设置成左子树的左子树
  • 第6步:把根节点的右子树设置成newNode
  • 最后,原来的值为8的节点(灰色)会被垃圾回收回收掉

1.3 双旋转

18722707-792003ff9edefdfe.png
图7

18722707-e959f42349ef0c8d.png
图8

如图7,将数列[2 ,1 , 6 ,5 ,7 , 3]构建成一棵AVL树,当插入3时,不再满足AVL的定义,需要左旋,但是左旋后的二叉树任然不满足平衡二叉树的定义;同理,如图8,将数列[10 , 11 , 7 , 6 , 8 , 9]构建成一颗AVL树,插入6后需要右旋,但是右旋后的二叉树任然不是AVL树;

对于以上两种情况需要进行双旋转处理

  • 对于 图7 这种情况,节点 "2" 的右子节点的左子树高度大于右子树高度,处理过程如下:

    • 先对这个节点(节点2)的右子树(节点6)进行右旋处理
    • 再对以节点2为根的树进行左旋处理
  • 对于 图8 这种情况,节点 "10" 的左子节点的右子树高度大于左子树高度,处理过程如下:

    • 先对这个节点(节点10)的左子树(节点7)进行左旋处理
    • 再对以节点10为根的树进行右旋处理
2.代码
package com.czy.datastructures.avl;

import lombok.ToString;

/**
 * @author chenzhiyuan
 * @date 2020-02-07 23:57
 */
public class AVLDemo {

    private Node root;

    /**
     * 返回以某个节点作为根节点的树的高度
     */
    private int height(Node childTreeRoot) {
        int leftMaxHeight = childTreeRoot.left == null ? 0 : height(childTreeRoot.left);
        int rightMaxHeight = childTreeRoot.right == null ? 0 : height(childTreeRoot.right);
        return Math.max(leftMaxHeight, rightMaxHeight) + 1;
    }

    /**
     * 返回某个节点的左子树的高度
     */
    private int leftChildTreeHeight(Node childTreeRoot) {
        return childTreeRoot.left == null ? 0 : height(childTreeRoot.left);
    }

    /**
     * 返回某个节点的右子树的高度
     */
    private int rightChildTreeHeight(Node childTreeRoot) {
        return childTreeRoot.right == null ? 0 : height(childTreeRoot.right);
    }

    /**
     * 给二叉排序树添加节点
     *
     * @param childTreeRoot 添加节点的树的根
     * @param newNode       被添加的节点
     */
    private void add(Node childTreeRoot, Node newNode) {
        if (this.root == null) {
            this.root = newNode;
            return;
        }

        if (newNode.data < childTreeRoot.data) {
            if (childTreeRoot.left == null) {
                Node node = new Node(newNode.data);
                node.position = Position.LEFT;
                childTreeRoot.left = node;
            } else {
                this.add(childTreeRoot.left, newNode);
            }
        } else {
            if (childTreeRoot.right == null) {
                Node node = new Node(newNode.data);
                node.position = Position.RIGHT;
                childTreeRoot.right = node;
            } else {
                this.add(childTreeRoot.right, newNode);
            }
        }

        // 判断是否需要左旋
        if (rightChildTreeHeight(childTreeRoot) - leftChildTreeHeight(childTreeRoot) > 1) {
            // 判断右子树是否需要右旋
            if (leftChildTreeHeight(childTreeRoot.right) > rightChildTreeHeight(childTreeRoot.right)) {
                this.rightRotate(childTreeRoot.right);
            }
            this.leftRotate(childTreeRoot);
            return;
        }

        // 判断是否需要右旋
        if (leftChildTreeHeight(childTreeRoot) - rightChildTreeHeight(childTreeRoot) > 1) {
            // 判断左子树是否需要左旋
            if (rightChildTreeHeight(childTreeRoot.left) > leftChildTreeHeight(childTreeRoot.left)) {
                this.leftRotate(childTreeRoot.left);
            }
            this.rightRotate(childTreeRoot);
        }
    }

    /**
     * 左旋(右子树高度 - 左子树高度 > 1)
     *
     * @param childTreeRoot 被左旋的树的根节点
     */
    private void leftRotate(Node childTreeRoot) {
        // 1.创建一个新节点newNode,新节点的值为childTreeRoot的值
        Node newNode = new Node(childTreeRoot.data);

        // 2.把newNode的左子树设置为childTreeRoot的左子树
        newNode.left = childTreeRoot.left;

        // 3.把新节点的右子树设置成childTreeRoot的右子树的左子树
        newNode.right = childTreeRoot.right.left;
        if (newNode.right != null) {
            newNode.right.position = Position.RIGHT;
        }

        // 4.把childTreeRoot的值替换成childTreeRoot的右子树
        childTreeRoot.data = childTreeRoot.right.data;

        // 5.把childTreeRoot的右子树设置成右子树的右子树
        childTreeRoot.right = childTreeRoot.right.right;

        // 6.把childTreeRoot的左子树设置成newNode
        newNode.position = Position.LEFT;
        childTreeRoot.left = newNode;
    }

    /**
     * 右旋(左子树高度 - 右子树高度 > 1)
     *
     * @param childTreeRoot 被右旋的树的根节点
     */
    private void rightRotate(Node childTreeRoot) {
        // 第1步:创建一个新节点newNode(红色),新节点的值为当前被右旋的树的根节点
        Node newNode = new Node(childTreeRoot.data);

        // 第2步:把newNode的右子树设置为根节点的右子树
        newNode.right = childTreeRoot.right;

        // 第3步:把newNode的左子树设置成根节点的左子树的右子树
        newNode.left = childTreeRoot.left.right;
        if (newNode.left != null) {
            newNode.left.position = Position.LEFT;
        }

        // 第4步:把根节点的值替换成根节点的左子节点的值
        childTreeRoot.data = childTreeRoot.left.data;

        // 第5步:把根节点的左子树设置成左子树的左子树
        childTreeRoot.left = childTreeRoot.left.left;

        // 第6步:把根节点的右子树设置成newNode
        newNode.position = Position.RIGHT;
        childTreeRoot.right = newNode;
    }

    /**
     * 前序遍历
     *
     * @param childTreeRoot 被遍历的子树的根
     */
    private void preOrderTraverse(Node childTreeRoot) {
        if (childTreeRoot == null) {
            return;
        }

        System.out.println(childTreeRoot.data + " " + childTreeRoot.position);
        this.preOrderTraverse(childTreeRoot.left);
        this.preOrderTraverse(childTreeRoot.right);
    }

    /**
     * 中序遍历
     *
     * @param childTreeRoot 被遍历的子树的根
     */
    private void inOrderTraverse(Node childTreeRoot) {
        if (childTreeRoot == null) {
            return;
        }

        this.inOrderTraverse(childTreeRoot.left);
        System.out.println(childTreeRoot.data + " " + childTreeRoot.position);
        this.inOrderTraverse(childTreeRoot.right);
    }

    /**
     * 节点定义
     */
    @ToString
    private static class Node {
        /**
         * 假设此demo中的node的data不会重复,后面会根据data来进行查询、删除等操作
         */
        private int data;
        private Node left;
        private Node right;
        private Position position;

        public Node(int value) {
            this.data = value;
        }
    }

    /**
     * 节点位置定义
     */
    private enum Position {
        LEFT,
        RIGHT
    }


    public static void main(String[] args) {
        AVLDemo demo = new AVLDemo();

        // 测试左旋
//        int[] leftRotate = {4, 3, 6, 5, 7, 8};
//        for (int i : leftRotate) {
//            demo.add(demo.root, new Node(i));
//        }

        // 测试右旋
//        int[] rightRotate = {10, 12, 8, 9, 7, 6};
//        for (int i : rightRotate) {
//            demo.add(demo.root, new Node(i));
//        }

        // 测试双旋转(先左旋后右选)
//        int[] doubleRotate = {10, 11, 7, 6, 8, 9};

        // 测试双旋转(先右旋后左旋)
        int[] doubleRotate = {2, 1, 6, 5, 7, 3};

        for (int i : doubleRotate) {
            demo.add(demo.root, new Node(i));
        }

        System.out.println("-------中序遍历-------");
        demo.inOrderTraverse(demo.root);
        System.out.println("-------前序遍历-------");
        demo.preOrderTraverse(demo.root);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值