平衡搜索樹——AVLTree

AVLTree

平衡搜索樹:AVL樹又稱爲高度平衡的二叉搜索樹


性質:
1. 左子樹和右子樹的高度之差的絕對值不超過1
2. 樹中的每個左子樹和右子樹都是AVL樹
3. 每個節點都有一個平衡因子(balance factor–bf),任一節點的平衡因子是-1,0,1。(每個節點的平衡因子等於右子樹的高度減去左子樹的高度)
4.左孩子的值<父節點<右孩子的值


一棵AVL樹有N個節點,其高度可以保持在lgN,插入/刪除/查找的時間複雜度也是lgN。每次的改變都要更新樹。下面我們主要討論下AVL樹的插入——


1.不做改變
2.左單旋
3. 右單旋
4.左右雙旋
5.右左雙旋


繪圖功底有限(圖略)看代碼


代碼實現

#pragma once
#include <iostream>
#include <cassert>
using namespace std;

template<class K, class V> // k = key 鍵   v = value 值
struct AVLTreeNode //結構體構造節點   三叉鏈
{
    K _key;
    V _value;
    AVLTreeNode<K, V>* _left;
    AVLTreeNode<K, V>* _right;
    AVLTreeNode<K, V>* _parent;

    int _bf;    // 平衡因子

    AVLTreeNode(const K& key, const V& value) // 拷貝構造
        :_left(NULL)
        , _right(NULL)
        , _parent(NULL)
        , _key(key)
        , _value(value)
        , _bf(0)
    {}
};

template<class K, class V>
class AVLTree
{
    typedef AVLTreeNode<K, V> Node;  //重命名 類中類
public:
    AVLTree() 
        :_root(NULL)
    {}

    bool Insert(const K& key, const V& value) //插入節點
    {
// 樹是否存在
        if (_root == NULL) 
        {
            _root = new Node(key, value);
            return true;
        }

        Node* parent = NULL;  // 根

// 樹是存在
        Node* cur = _root;
        while (cur) //尋找節點應該去的位置
        {
            if (cur->_key > key) // 小於根 往左走
            {
                parent = cur;
                cur = cur->_left;
            }
            else if (cur->_key < key) // 大於根  往右走
            {
                parent = cur;
                cur = cur->_right;
            }
            else
            {
                return false;
            }
        }

        cur = new Node(key, value); // cur的位置即爲應在位置 

//完成新節點三叉鏈的鏈接
        if (parent->_key < key)
        {
            parent->_right = cur;
            cur->_parent = parent;
        }
        else
        {
            parent->_left = cur;
            cur->_parent = parent;
        }

        // 調平衡

// 1.更新AVL整棵樹的平衡因子
        while (parent)//插入節點的父節點
        {
            // 更新parent的平衡因子
            if (cur == parent->_right) 
                parent->_bf++; //bf = 右高度 - 左高度
            else
                parent->_bf--;

            // 遞歸往上
            // cur沒有兄弟
            if (parent->_bf == -1 || parent->_bf == 1)//bf取值範圍 -2,-1,0,1,2
            {
                cur = parent;
                parent = parent->_parent;
            }
            else if (parent->_bf == 0) // 有兄弟 其餘平衡因子不變
            {
                break;
            }
            else // -2/2  
            {
                // 旋轉
                if (parent->_bf == 2) 
                {
                    if (cur->_bf == 1) 
                    {
                        RotateL(parent);
                    }
                    else // -1
                    {
                        RotateRL(parent);
                    }
                }
                else // -2
                {
                    if (cur->_bf == -1)
                    {
                        RotateR(parent);
                    }
                    else
                    {
                        RotateLR(parent);
                    }
                }

                break;
            }
        }

        return true;
    }

//左單旋
    void RotateL(Node* parent)
    {
        Node* subR = parent->_right;
        Node* subRL = subR->_left;
        Node* ppNode = parent->_parent;

        parent->_right = subRL;
        if (subRL) //subRL  即爲空 上面代碼仍成立
            subRL->_parent = parent;

        subR->_left = parent;
        parent->_parent = subR;

        if (parent == _root) //判斷是否爲根節點
        {
            _root = subR;
            _root->_parent = NULL;
        }
        else
        {
            if (ppNode->_left == parent) //parent 位於其父節點的左邊 
            {
                ppNode->_left = subR;
            }
            else
            {
                ppNode->_right = subR;
            }

            subR->_parent = ppNode; //無論是否存在祖父節點 統一指向其
        }

        parent->_bf = subR->_bf = 0; // 平衡因子制0
    }

    // 右單旋  
    void RotateR(Node* parent)
    {
        Node* subL = parent->_left;
        Node* subLR = subL->_right;
        Node* ppNode = parent->_parent;

        parent->_left = subLR;
        if (subLR)
            subLR->_parent = parent;

        subL->_right = parent;
        parent->_parent = subL;

        if (_root == parent)
        {
            _root = subL;
            subL->_parent = NULL;
        }
        else
        {
            if (ppNode->_right == parent)
            {
                ppNode->_right = subL;
            }
            else
            {
                ppNode->_left = subL;
            }

            subL->_parent = ppNode;
        }

        subL->_bf = parent->_bf = 0;
    }


// 左右單旋
    void RotateLR(Node* parent)
    {
        Node* subL = parent->_left;
        Node* subLR = subL->_right;
        int bf = subLR->_bf;  // 前面兩個的最終平衡因子與subLR有關

        RotateL(parent->_left); //左旋
        RotateR(parent); //右旋

        if (bf == 0)
        {
            subLR->_bf = subL->_bf = parent->_bf = 0;
        }
        else if (bf == 1)
        {
            parent->_bf = 0;
            subL->_bf = -1;
            subLR->_bf = 0;
        }
        else if (bf == -1)
        {
            parent->_bf = 1;
            subL->_bf = 0;
            subLR->_bf = 0;
        }
        else
        {
            assert(false);
        }
    }

    //右左單旋
    void RotateRL(Node* parent)
    {
        Node* subR = parent->_right;
        Node* subRL = subR->_left;
        int bf = subRL->_bf;

        RotateR(parent->_right);
        RotateL(parent);

        if (bf == 0)
        {
            subRL->_bf = subR->_bf = parent->_bf = 0;
        }
        else if (bf == 1)
        {
            subR->_bf = 0;
            parent->_bf = -1;
            subRL->_bf = 0;
        }
        else if (bf == -1)
        {
            parent->_bf = 0;
            subR->_bf = 1;
            subRL->_bf = 0;
        }
        else
        {
            assert(false);
        }
    }


//打印 遞歸打印需要兩個函數體
    void _InOrder(Node* root)
    {
        if (root == NULL)
        {
            return;
        }

        _InOrder(root->_left);
        cout << root->_key << " ";
        _InOrder(root->_right);

    }

    void InOrder()
    {
        _InOrder(_root);
        cout << endl;
    }

//檢測是否平衡 

////////////////////////////////////////////////////////////////
//優化爲時間複雜度 O(N)  故要傳高度  優化遞歸  左右中  中序遍歷  
////////////////////////////////////////////////////////////////
    bool _IsBalance(Node* root, int& height) // 傳根和高度
    {
        if (root == NULL) //遞歸出口 葉子節點
        {
            height = 0;
            return true;
        }

        int leftHeight = 0;
        int rightHeight = 0;
        if (_IsBalance(root->_left, leftHeight)
            && _IsBalance(root->_right, rightHeight))
        {
            if (rightHeight - leftHeight != root->_bf)
            {
                cout << "平衡因子異常" << root->_key << endl;
                return false;
            }

            height = leftHeight > rightHeight ? \
                leftHeight + 1 : rightHeight + 1;
            return abs(leftHeight - rightHeight) < 2; //abs()取絕對值
            //若返回false則不是AVL樹
        }
        else
        {
            return false;
        }
    }

    bool IsBalance()
    {
        int height = 0;
        return _IsBalance(_root, height);
    }

private:
    Node* _root;
};



void TestAVLtree()
{
    int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14 };
    //int a[] = {16, 3, 7, 11, 9, 26, 18, 14, 15};
    AVLTree<int, int> t;
    for (size_t i = 0; i < sizeof(a) / sizeof(int); ++i)
    {
        t.Insert(a[i], i);
        cout << a[i] << ":" << t.IsBalance() << endl;
    }

    t.InOrder();
    cout <<"Is Balance:"<< t.IsBalance() << endl;
}

RBTree(紅黑樹):https://blog.csdn.net/Romantic_C/article/details/81263820

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章