算法導論:二叉搜索樹模板

今天看了算法導論的第12章《二叉搜索樹》,覺得裏面的過程的僞代碼很精巧,過程講解也很仔細易懂,所以就寫下這個二叉搜索樹模板。

樹類數據結構的關鍵操作是插入和刪除,查找和遍歷相對而言技巧性和難度一般吧。

插入

在一個while循環裏,從root開始不斷往下走(根據左小右大的特點),找到要插入的位置,插進去就好了。
找要插入的位置的過程其實跟查找是一樣的。

插入後不用管樹平衡與否,所以還是很簡單的。

一個小細節:注意插入第一個結點的時候,要更新root!

bool insert(const T& value) {
    TreeNode<T> *lastNode = NULL, *now = m_root, *toInsert = new TreeNode<T>(value);
    while (now != NULL) {
        lastNode = now;
        if (value == now->value)
            return false;
        else if (value < now->value)
            now = now->left;
        else
            now = now->right;
    }

    toInsert->parent = lastNode;
    if (lastNode == NULL) {
        m_root = toInsert;
    }
    else if (value < lastNode->value) {
        lastNode->left = toInsert;
    }
    else {
        lastNode->right = toInsert;
    }
    return true;
}

刪除

對要刪除的結點node分四種情況(但是實現的時候不需要這樣劃分,具體見代碼):
1. node是葉子結點,直接刪了,不會影響搜索樹的性質,要更新其父結點的孩子(也就是自己相當於變成NULL了);
2. node只有左孩子或只有右孩子,這個也很簡單,刪除相當於把左/右孩子提起來,放在自己原來的位置就好了;
3. node既有左孩子也有右孩子,需要找到樹中比node的值大的結點中,值最小的一個來替代node(想想爲什麼),其實只需要從node的右孩子一直往左走就可以了(見getTreeMinimum函數),這也是二叉搜索樹的特性決定的!

綜合上面的分析,每一種情況都需要把某個結點來替換另外一個結點的位置,所以就產生了transplant輔助函數了!transplant的意思是手術、移植,一個結點其實代表了以它爲根的子樹,所以相當於把一棵子樹移植到另一棵子樹的位置上去,它的實現也很容易理解:

void transplant(TreeNode<T>* from, TreeNode<T>* to) {
    if (from->parent == NULL) {
        m_root = to;
    } else if (from == from->parent->left) {
        from->parent->left = to;
    } else {
        from->parent->right = to;
    }
    if (to != NULL) {
        to->parent = from->parent;
    }
}

下面是刪除邏輯的實現:

bool deleteNode(TreeNode<T>* node) {
    if (node == NULL)
        return false;

    if (node->left == NULL) {
        transplant(node, node->right);
    } else if (node->right == NULL) {
        transplant(node, node->left);
    } else {
        TreeNode<T>* newSubRoot = getTreeMinimum(node->right);
        if (newSubRoot->parent != node) {
            transplant(newSubRoot, newSubRoot->right);
            newSubRoot->right = node->right;
            node->right->parent = newSubRoot;
        }
        transplant(node, newSubRoot);
        newSubRoot->left = node->left;
        node->left->parent = newSubRoot;
    }
    delete node;
    return true;
}

所有代碼

// BinarySearchTree.h
#ifndef __BINARY_SEARCH_TREE_H__
#define __BINARY_SEARCH_TREE_H__

#include <stdlib.h>
#include <iostream>
using namespace std;


template<typename T>
struct TreeNode
{
    T value;
    TreeNode *left, *right, *parent;
    TreeNode(const T& value)
    : value(value), left(NULL), right(NULL), parent(NULL) {}
};


template<typename T>
class BinarySearchTree
{
public:
    BinarySearchTree() {
        m_root = NULL;
    }

    size_t height() const {
        return getHeight(m_root);
    }

    // 返回是否插入成功,若有重複則插入失敗,則只保留已有的結點
    bool insert(const T& value) {
        TreeNode<T> *lastNode = NULL, *now = m_root, *toInsert = new TreeNode<T>(value);
        while (now != NULL) {
            lastNode = now;
            if (value == now->value)
                return false;
            else if (value < now->value)
                now = now->left;
            else
                now = now->right;
        }

        toInsert->parent = lastNode;
        if (lastNode == NULL) {
            m_root = toInsert;
        }
        else if (value < lastNode->value) {
            lastNode->left = toInsert;
        }
        else {
            lastNode->right = toInsert;
        }
        return true;
    }

    // 返回是否刪除成功,不成功的原因是:沒有這個值
    bool deleteNode(const T& value) {
        TreeNode<T> *now = m_root;
        while (now != NULL) {
            if (value == now->value)
                return deleteNode(now);
            else if (value < now->value)
                now = now->left;
            else
                now = now->right;
        }
        return false;
    }

    bool deleteNode(TreeNode<T>* node) {
        if (node == NULL)
            return false;

        if (node->left == NULL) {
            transplant(node, node->right);
        } else if (node->right == NULL) {
            transplant(node, node->left);
        } else {
            TreeNode<T>* newSubRoot = getTreeMinimum(node->right);
            if (newSubRoot->parent != node) {
                transplant(newSubRoot, newSubRoot->right);
                newSubRoot->right = node->right;
                node->right->parent = newSubRoot;
            }
            transplant(node, newSubRoot);
            newSubRoot->left = node->left;
            node->left->parent = newSubRoot;
        }
        // delete node;
        return true;
    }

    // 若返回NULL則表示找不到
    TreeNode<T>* find(const T& value) const {
        TreeNode<T> *now = m_root;
        while (now != NULL) {
            if (value == now->value)
                return now;
            else if (value < now->value)
                now = now->left;
            else
                now = now->right;
        }
        return NULL;
    }

    // 前序輸出
    void display(char spliter=' ') const {
        if (m_root == NULL) {
            cout << "NULL" << endl;
            return;
        }
        displayHelper(m_root, spliter);
        cout << endl;
    }


private:
    void transplant(TreeNode<T>* from, TreeNode<T>* to) {
        if (from->parent == NULL) {
            m_root = to;
        } else if (from == from->parent->left) {
            from->parent->left = to;
        } else {
            from->parent->right = to;
        }
        if (to != NULL) {
            to->parent = from->parent;
        }
    }

    size_t getHeight(const TreeNode<T>* root) const {
        if (root == NULL)
            return 0;
        size_t left_height = getHeight(root->left);
        size_t right_height = getHeight(root->right);
        return max(left_height, right_height) + 1;
    }

    void displayHelper(TreeNode<T>* root, char spliter) const {
        if (root == NULL)
            return;
        displayHelper(root->left, spliter);
        cout << root->value << spliter;
        displayHelper(root->right, spliter);
    }

    TreeNode<T>* getTreeMinimum(TreeNode<T>* root) const {
        TreeNode<T>* now = root;
        while (now->left != NULL)
            now = now->left;
        return now;
    }


private:
    TreeNode<T>* m_root;
};

#endif

下面是測試和使用的例子:

#include "BinarySearchTree.h"
#include <iostream>
#include <stdlib.h>
#include <ctime>
using namespace std;


inline int randInt() {
    static const int MAX = 9;
    return rand() % MAX;
}


int main() {
    srand(time(0));

    BinarySearchTree<int> bst;
    for (int i = 0; i < 10; ++i)
        bst.insert(randInt());
    bst.display();
    cout << "tree height = " << bst.height() << endl << endl;

    for (int i = 0; i < 10; ++i) {
        bool result = bst.deleteNode(i);
        if (result)
            cout << "delete success " << i << endl;
        else
            cout << "delete fail " << i << endl;
        bst.display();
        cout << endl;
    }

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