美文网首页
数据结构-AVL树

数据结构-AVL树

作者: 鼬殿 | 来源:发表于2020-06-06 11:52 被阅读0次

    平衡(Balance)

    当节点数量固定时,左右子树的高度越接近,这棵二叉树就越平衡(高度越低)


    平衡二叉搜索树(Balanced Binary Search Tree)

    英文简称为:BBST
    经典常见的平衡二叉搜索树有

    AVL树

    • Windows NT 内核中广泛使用

    红黑树

    • C++ STL(比如 map、set )
    • Java 的 TreeMap、TreeSet、HashMap、HashSet
    • Linux 的进程调度
    • Ngix 的 timer 管理

    一般也称它们为:自平衡的二叉搜索树(Self-balancing Binary Search Tree)

    AVL树

    AVL树是最早发明的自平衡二叉搜索树之一

    ◼ AVL 取名于两位发明者的名字
    G. M. Adelson-Velsky 和 E. M. Landis(来自苏联的科学家)

    ◼ 平衡因子(Balance Factor):某结点的左右子树的高度差

    AVL树的特点:

    • 每个节点的平衡因子只可能是 10-1(绝对值 ≤ 1,如果超过 1,称之为“失衡”)
    • 每个节点的左右子树高度差不超过 1
    • 搜索、添加、删除的时间复杂度是 O(logn)

    平衡对比

    输入数据:35, 37, 34, 56, 25, 62, 57, 9, 74, 32, 94, 80, 75, 100, 16, 82


    简单的继承结构

    添加导致的失衡

    示例:往下面这棵子树中添加 13
    ◼ 最坏情况:可能会导致所有祖先节点都失衡
    ◼ 父节点、非祖先节点,都不可能失衡


    LL – 右旋转(单旋)

    g.left = p.right
    p.right = g
    ◼ 让p成为这棵子树的根节点
    ◼ 仍然是一棵二叉搜索树:T0 < n < T1 < p < T2 < g < T3
    ◼ 整棵树都达到平衡


    还需要注意维护的内容
    T2pgparent 属性
    先后更新 gp 的高度

    RR – 左旋转(单旋)

    g.right = p.left
    p.left = g
    ◼ 让p成为这棵子树的根节点
    ◼ 仍然是一棵二叉搜索树:T0 < g < T1 < p < T2 < n < T3
    ◼ 整棵 都达到平衡


    还需要注意维护的内容
    T1pgparent 属性
    先后更新 gp 的高度

    LR – RR左旋转,LL右旋转(双旋)

    RL – LL右旋转,RR左旋转(双旋)

    代码

    AVL树恢复平衡的动作是在二叉搜索树添加完元素之后

    • 普通二叉树代码
    package com.njf;
    
    import java.util.LinkedList;
    import java.util.Queue;
    
    import com.njf.BinaryTree.Node;
    
    import njf.printer.BinaryTreeInfo;
    
    @SuppressWarnings("unchecked")
    public class BinaryTree<E> implements BinaryTreeInfo {
        protected int size;
        protected Node<E> root;
        
        public int size() {
            return size;
        }
    
        public boolean isEmpty() {
            return size == 0;
        }
    
        public void clear() {
            root = null;
            size = 0;
        }
        
        public void preorder(Visitor<E> visitor) {
            if (visitor == null) return;
            preorder(root, visitor);
        }
        
        private void preorder(Node<E> node, Visitor<E> visitor) {
            if (node == null || visitor.stop) return;
            
            visitor.stop = visitor.visit(node.element);
            preorder(node.left, visitor);
            preorder(node.right, visitor);
        }
        
        public void inorder(Visitor<E> visitor) {
            if (visitor == null) return;
            inorder(root, visitor);
        }
        
        private void inorder(Node<E> node, Visitor<E> visitor) {
            if (node == null || visitor.stop) return;
            
            inorder(node.left, visitor);
            if (visitor.stop) return;
            visitor.stop = visitor.visit(node.element);
            inorder(node.right, visitor);
        }
        
        public void postorder(Visitor<E> visitor) {
            if (visitor == null) return;
            postorder(root, visitor);
        }
        
        private void postorder(Node<E> node, Visitor<E> visitor) {
            if (node == null || visitor.stop) return;
            
            postorder(node.left, visitor);
            postorder(node.right, visitor);
            if (visitor.stop) return;
            visitor.stop = visitor.visit(node.element);
        }
        
        public void levelOrder(Visitor<E> visitor) {
            if (root == null || visitor == null) return;
            
            Queue<Node<E>> queue = new LinkedList<>();
            queue.offer(root);
            
            while (!queue.isEmpty()) {
                Node<E> node = queue.poll();
                if (visitor.visit(node.element)) return;
                
                if (node.left != null) {
                    queue.offer(node.left);
                }
                
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        
        public boolean isComplete() {
            if (root == null) return false;
            Queue<Node<E>> queue = new LinkedList<>();
            queue.offer(root);
            
            boolean leaf = false;
            while (!queue.isEmpty()) {
                Node<E> node = queue.poll();
                if (leaf && !node.isLeaf()) return false;
    
                if (node.left != null) {
                    queue.offer(node.left);
                } else if (node.right != null) {
                    return false;
                }
                
                if (node.right != null) {
                    queue.offer(node.right);
                } else { // 后面遍历的节点都必须是叶子节点
                    leaf = true;
                }
            }
            
            return true;
        }
        
        public int height() {
            if (root == null) return 0;
            
            // 树的高度
            int height = 0;
            // 存储着每一层的元素数量
            int levelSize = 1;
            Queue<Node<E>> queue = new LinkedList<>();
            queue.offer(root);
            
            while (!queue.isEmpty()) {
                Node<E> node = queue.poll();
                levelSize--;
                
                if (node.left != null) {
                    queue.offer(node.left);
                }
                
                if (node.right != null) {
                    queue.offer(node.right);
                }
    
                if (levelSize == 0) { // 意味着即将要访问下一层
                    levelSize = queue.size();
                    height++;
                }
            }
            
            return height;
        }
        
        public int height2() {
            return height(root);
        }
        
        private int height(Node<E> node) {
            if (node == null) return 0;
            return 1 + Math.max(height(node.left), height(node.right));
        }
        
        protected Node<E> creatNode(E element, Node<E> parent) {
            return new Node<>(element, parent);
        }
    
        protected Node<E> predecessor(Node<E> node) {
            if (node == null) return null;
            
            // 前驱节点在左子树当中(left.right.right.right....)
            Node<E> p = node.left;
            if (p != null) {
                while (p.right != null) {
                    p = p.right;
                }
                return p;
            }
            
            // 从父节点、祖父节点中寻找前驱节点
            while (node.parent != null && node == node.parent.left) {
                node = node.parent;
            }
    
            // node.parent == null
            // node == node.parent.right
            return node.parent;
        }
        
        protected Node<E> successor(Node<E> node) {
            if (node == null) return null;
            
            // 前驱节点在左子树当中(right.left.left.left....)
            Node<E> p = node.right;
            if (p != null) {
                while (p.left != null) {
                    p = p.left;
                }
                return p;
            }
            
            // 从父节点、祖父节点中寻找前驱节点
            while (node.parent != null && node == node.parent.right) {
                node = node.parent;
            }
    
            return node.parent;
        }
    
        public static abstract class Visitor<E> {
            boolean stop;
            /**
             * @return 如果返回true,就代表停止遍历
             */
            abstract boolean visit(E element);
        }
        
        protected static class Node<E> {
            E element;
            Node<E> left;
            Node<E> right;
            Node<E> parent;
            public Node(E element, Node<E> parent) {
                this.element = element;
                this.parent = parent;
            }
            public boolean isLeaf() {
                return left == null && right == null;
            }
            public boolean hasTwoChildren() {
                return left != null && right != null;
            }
            public boolean isLeftChild() {
                return parent != null && this == parent.left; 
            }
            public boolean isRightChild() {
                return parent != null && this == parent.right; 
            }
        }
        
        /*****************************二叉树的打印***************/
        @Override
        public Object root() {
            return root;
        }
    
        @Override
        public Object left(Object node) {
            return ((Node<E>)node).left;
        }
    
        @Override
        public Object right(Object node) {
            return ((Node<E>)node).right;
        }
    
        @Override
        public Object string(Object node) {
            return node;
        }
    }
    
    • 二叉搜索树代码
    package com.njf;
    
    import java.util.Comparator;
    
    @SuppressWarnings("unchecked")
    public class BST<E> extends BinaryTree<E> {
        private Comparator<E> comparator;
        
        public BST() {
            this(null);
        }
        
        public BST(Comparator<E> comparator) {
            this.comparator = comparator;
        }
    
        public void add(E element) {
            elementNotNullCheck(element);
            // 添加第一个节点
            if (root == null) {
                root = creatNode(element, null);
                size++;
                // 新添加节点之后的处理
                afterAdd(root);
                return;
            }
            
            // 添加的不是第一个节点
            // 找到父节点
            Node<E> parent = root;
            Node<E> node = root;
            int cmp = 0;
            do {
                cmp = compare(element, node.element);
                parent = node;
                if (cmp > 0) {
                    node = node.right;
                } else if (cmp < 0) {
                    node = node.left;
                } else { // 相等
                    node.element = element;
                    return;
                }
            } while (node != null);
    
            // 看看插入到父节点的哪个位置
            Node<E> newNode = creatNode(element, parent);
            if (cmp > 0) {
                parent.right = newNode;
            } else {
                parent.left = newNode;
            }
            size++;
            // 新添加节点之后的处理
            afterAdd(newNode);
        }
        
        /**
         * 添加node之后的调整
         * @param node 新添加的节点
         */
        protected void afterAdd(Node<E> node) {}
        
        /**
         * remove node之后的调整
         * @param node 移除节点
         */
        protected void afterRemove(Node<E> node) {}
    
        public void remove(E element) {
            remove(node(element));
        }
    
        public boolean contains(E element) {
            return node(element) != null;
        }
        
        private void remove(Node<E> node) {
            if (node == null) return;
            size--;
            if (node.hasTwoChildren()) { // 度为2的节点
                // 找到后继节点
                Node<E> s = successor(node);
                // 用后继节点的值覆盖度为2的节点的值
                node.element = s.element;
                // 删除后继节点
                node = s;
            }
            
            // 删除node节点(node的度必然是1或者0)
            Node<E> replacement = node.left != null ? node.left : node.right;
            
            if (replacement != null) { // node是度为1的节点
                // 更改parent
                replacement.parent = node.parent;
                // 更改parent的left、right的指向
                if (node.parent == null) { // node是度为1的节点并且是根节点
                    root = replacement;
                } else if (node == node.parent.left) {
                    node.parent.left = replacement;
                } else { // node == node.parent.right
                    node.parent.right = replacement;
                }
                afterRemove(node);
            } else if (node.parent == null) { // node是叶子节点并且是根节点
                root = null;
                afterRemove(node);
            } else { // node是叶子节点,但不是根节点
                if (node == node.parent.left) {
                    node.parent.left = null;
                } else { // node == node.parent.right
                    node.parent.right = null;
                }
                afterRemove(node);
            }
        }
        
        private Node<E> node(E element) {
            Node<E> node = root;
            while (node != null) {
                int cmp = compare(element, node.element);
                if (cmp == 0) return node;
                if (cmp > 0) {
                    node = node.right;
                } else { // cmp < 0
                    node = node.left;
                }
            }
            return null;
        }
        
        /**
         * @return 返回值等于0,代表e1和e2相等;返回值大于0,代表e1大于e2;返回值小于于0,代表e1小于e2
         */
        private int compare(E e1, E e2) {
            if (comparator != null) {
                return comparator.compare(e1, e2);
            }
            return ((Comparable<E>)e1).compareTo(e2);
        }
        
        private void elementNotNullCheck(E element) {
            if (element == null) {
                throw new IllegalArgumentException("element must not be null");
            }
        }
    }
    
    
    • AVLTree
    package com.njf;
    
    import java.util.Comparator;
    
    public class AVLTree<E> extends BST<E>{
        public AVLTree() {
            this(null);
        }
        
        public AVLTree(Comparator<E> comparator) {
            super(comparator);
        }
        
        @Override
        protected void afterAdd(Node<E> node) {
            while ((node = node.parent) != null) {//往上一直寻找父结点
                if (isBalanced(node)) {//判断结点是否平衡
                    //更新高度
                    updateNodeHeight(node);
                }else {
                    // 恢复平衡
                    rebalance(node);
                    // 整棵树恢复平衡
                    break;
                }   
            }
        }
    
        @Override
        protected void afterRemove(Node<E> node) {
            while ((node = node.parent) != null) {//往上一直寻找父结点
                if (isBalanced(node)) {//判断结点是否平衡
                    //更新高度
                    updateNodeHeight(node);
                }else {
                    // 恢复平衡
                    rebalance(node);
                }   
            }
        }
    
        /**
         * 恢复平衡
         * @param grand 高度最低的那个不平衡节点
         */
        private void rebalance(Node<E> grand) {
            //parent是grand左右子树高的结点
            Node<E> parent = ((AVLNode<E>)grand).tallerChild();
            //node是parent左右子树高的结点
            Node<E> node = ((AVLNode<E>)parent).tallerChild();
            if (parent.isLeftChild()) {//L
                if (node.isLeftChild()) {//LL
                    rotateRight(grand);
                }else {//LR
                    rotateLeft(parent);
                    rotateRight(grand);
                }
            }else {//R
                if (node.isLeftChild()) {//RL
                    rotateRight(parent);
                    rotateLeft(grand);
                }else {//RR
                    rotateLeft(grand);
                }
            }
        }
        
        /**
         * 左旋转
         * @param grand 高度最低的那个不平衡节点
         */
        private void rotateLeft(Node<E> grand) {
            Node<E> parent = grand.right;
            Node<E> child = parent.left;
            grand.right = child;
            parent.left = grand;
            //让parent成为这棵子树的根节点
            afterRotate(grand, parent, child);
        }
        
        /**
         * 右旋转
         * @param grand 高度最低的那个不平衡节点
         */
        private void rotateRight(Node<E> grand) {
            Node<E> parent = grand.left;
            Node<E> child = parent.right;
            grand.left = parent.right;
            parent.right = grand;
            afterRotate(grand, parent, child);
        }
        
        private void afterRotate(Node<E> grand, Node<E> parent, Node<E> child) {
            //让parent成为这棵子树的根节点
            parent.parent = grand.parent;
            if (grand.isLeftChild()) {
                grand.parent.left = parent;
            }else if (grand.isRightChild()) {
                grand.parent.right = parent;
            }else {
                root = parent;
            }
            //更新child的parent
            if (child != null) {
                child.parent = grand;
            }
            //更新grand的parent
            grand.parent = parent;
            //更新结点的高度
            updateNodeHeight(grand);
            updateNodeHeight(parent);
        }
        
        /**
         * 右旋转
         * @param node 更新结点的高度
         */
        private void updateNodeHeight(Node<E> node) {
            ((AVLNode<E>)node).updateNodeHeight();
        }
        
        /**
         * 右旋转
         * @param node 判断结点是否平衡
         */
        private boolean isBalanced(Node<E> node) {
            return Math.abs(((AVLNode<E>)node).balanceFactor()) <= 1;
        }
        
        @Override
        protected Node<E> creatNode(E element, Node<E> parent) {
            return new AVLNode(element,parent);
        }
        
        private static class AVLNode<E> extends Node<E>{
            //每个新添加的结点都是叶子结点,所以初始高度是1(由于每次添加新结点都会判断是否恢复平衡,所以在添加新结点之前,一定是avl树);
            int height = 1;
            public AVLNode(E element, Node<E> parent) {
                super(element, parent);
            }
            //平衡因子
            public int balanceFactor() {
                int leftHeight = left == null ? 0 : ((AVLNode<E>)left).height;
                int rightHeight = right == null ? 0 : ((AVLNode<E>)right).height;
                return leftHeight - rightHeight;
            }
            public void updateNodeHeight() {//更新结点的高度都是要添加结点的父结点的高度
                int leftHeight = left == null ? 0 : ((AVLNode<E>)left).height;
                int rightHeight = right == null ? 0 : ((AVLNode<E>)right).height;
                height = 1 + Math.max(leftHeight,rightHeight);
            }
            public Node<E> tallerChild() {
                int leftHeight = left == null ? 0 : ((AVLNode<E>)left).height;
                int rightHeight = right == null ? 0 : ((AVLNode<E>)right).height;
                if (leftHeight > rightHeight) return left;
                if (leftHeight < rightHeight) return right;
                //如果当前结点左右子树一样高,返回跟当前结点方向一致的子树(当前结点是父结点的左子树,就返回当前结点的左子树,否则返回右子树)
                return isLeftChild() ? left : right;
            }
            
            @Override
            public String toString() {
                String parentString = "null";
                if (parent != null) {
                    parentString = parent.element.toString();
                }
                return element + "_p(" + parentString + ")_h(" + height + ")";
            }
        }
    }
    
    • AVLTree代码验证
    package com.njf;
    
    import java.util.Comparator;
    
    import njf.printer.BinaryTrees;
    
    public class Main {
        
        static void test1() {
            Integer data[] = new Integer[] {
                    67, 52, 92, 96, 53, 95, 13, 63, 34, 82, 76, 54, 9, 68, 39
            };
            AVLTree<Integer> avl = new AVLTree<>();
            for (int i = 0; i < data.length; i++) {
                avl.add(data[i]);
            }
            BinaryTrees.println(avl);
        }
    
        public static void main(String[] args) {
            test1();
        }
    }
    

    下面是打印的AVL树

                                  ┌───────────────────67_p(null)_h(5)───────────────────┐
                                  │                                                     │
                  ┌─────────52_p(67)_h(4)─────────┐                             ┌─82_p(67)_h(3)─┐
                  │                               │                             │               │
          ┌─13_p(52)_h(3)─┐               ┌─54_p(52)_h(2)─┐             ┌─76_p(82)_h(2) ┌─95_p(82)_h(2)─┐
          │               │               │               │             │               │               │
    9_p(13)_h(1)    34_p(13)_h(2)─┐ 53_p(54)_h(1)   63_p(54)_h(1) 68_p(76)_h(1)   92_p(95)_h(1)   96_p(95)_h(1)
                                  │
                            39_p(34)_h(1)
    

    统一所有旋转操作


    从上图中可以看到所有旋转最后得到的结果都是一样的
    代码如下:

        /**
         * 恢复平衡
         * @param grand 高度最低的那个不平衡节点
         */
        private void rebalance(Node<E> grand) {
            //parent是grand左右子树高的结点
            Node<E> parent = ((AVLNode<E>)grand).tallerChild();
            //node是parent左右子树高的结点
            Node<E> node = ((AVLNode<E>)parent).tallerChild();
            if (parent.isLeftChild()) { // L
                if (node.isLeftChild()) { // LL
                    rotate(grand, node, node.right, parent, parent.right, grand);
                } else { // LR
                    rotate(grand, parent, node.left, node, node.right, grand);
                }
            } else { // R
                if (node.isLeftChild()) { // RL
                    rotate(grand, grand, node.left, node, node.right, parent);
                } else { // RR
                    rotate(grand, grand, parent.left, parent, node.left, node);
                }
            }
        }
        
        private void rotate(
                Node<E> r, // 子树的根节点
                Node<E> b, Node<E> c,
                Node<E> d,
                Node<E> e, Node<E> f) {
            // 让d成为这棵子树的根节点
            d.parent = r.parent;
            if (r.isLeftChild()) {
                r.parent.left = d;
            } else if (r.isRightChild()) {
                r.parent.right = d;
            } else {
                root = d;
            }
            
            //b-c
            b.right = c;
            if (c != null) {
                c.parent = b;
            }
            updateNodeHeight(b);
            
            // e-f
            f.left = e;
            if (e != null) {
                e.parent = f;
            }
            updateNodeHeight(f);
            
            // b-d-f
            d.left = b;
            d.right = f;
            b.parent = d;
            f.parent = d;
            updateNodeHeight(d);
        }
    

    删除导致的失衡

    ◼ 示例:删除子树中的 16
    ◼ 可能会导致父结点祖先结点失衡(只有1个结点会失衡),其他结点,都不可能失衡

    11结点的高度没有变

    LL – 右旋转(单旋)

    ◼ 如果绿色节点不存在,更高层的祖先节点可能也会失衡,需要再次恢复平衡,然后又可能导致更高层的祖先节点失衡...
    ◼ 极端情况下,所有祖先节点都需要进行恢复平衡的操作,共 O(logn) 次调整

    红色块是删除的结点,在经过旋转之后,如果绿色块结点不存在,P结点的高度是-1的,所以可能导致更上层结点的失衡

    RR – 左旋转(单旋)

    LR – RR左旋转,LL右旋转(双旋)

    RL – LL右旋转,RR左旋转(双旋)


    代码部分:
        @Override
        protected void afterRemove(Node<E> node) {
            while ((node = node.parent) != null) {//往上一直寻找父结点
                if (isBalanced(node)) {//判断结点是否平衡
                    //更新高度
                    updateNodeHeight(node);
                }else {
                    // 恢复平衡
                    rebalance(node);
                }   
            }
        }
    

    相关文章

      网友评论

          本文标题:数据结构-AVL树

          本文链接:https://www.haomeiwen.com/subject/wkaazhtx.html