您的位置:首页 > 其它

二叉排序树(BinarySortTree)的实现

2013-03-16 20:57 295 查看
/*
    Title : Binary Sort Tree
    Author: nyist_xiaod
    Date  : 2013.3.16
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

#define BSTdef
#define Pnn pair<Node*,Node*>

#ifdef BSTdef
#define Pre(root,parent) (root==Root ? Root : (value < parent->value ? parent->lson : parent->rson))
#endif

template<typename T>
struct BST
{
    struct Node
    {
        T value;
        Node *lson, *rson;
        Node(const T& val):value(val),lson(NULL),rson(NULL){}
    };
    Node* Root;
    /**********************************************/
    BST():Root(NULL){}
    bool empty()
    {
        return Root == NULL;
    }
    void clear(Node* root)
    {
        if(root == NULL)
            return ;
        clear(root->lson);
        clear(root->rson);
        delete root;
        root = NULL;
    }
    Node* least(Node* root)
    {
        return root->lson ? least(root->lson) : root;
    }
    Node* most(Node* root)
    {
        return root->rson ? most(root->rson) : root;
    }
    Pnn search(const T& value)
    {
        Node *root = Root , *parent = NULL;
        while(root)
        {
            if(value == root->value)
                return make_pair(root,parent);
            parent = root;
            root = value < parent->value ? parent->lson : parent->rson;
        }
        return make_pair(root,parent);
    }
    bool insert(const T& value)
    {
        Pnn p = search(value);
        Node *root = p.first , *parent = p.second;
        if(root != NULL)
            return false;
        Pre(root,parent) = new Node(value);
        return true;
    }
    void erase(const T& value)
    {
        Pnn p = search(value);
        Node *root = p.first , *parent = p.second;
        if(root->lson == NULL)
            Pre(root,parent) = root->rson;
        else
            if(root->rson == NULL)
                Pre(root,parent) = root->lson;
            else
            {
                Node *lmost = root->lson, *lparent = root;
                while(lmost->rson)
                {
                    lparent = lmost;
                    lmost = lmost->rson;
                }
                (lmost->value < lparent->value ? lparent->lson : lparent->rson) = lmost->lson;
                lmost->lson = root->lson , lmost->rson = root->rson;
                Pre(root,parent) = lmost;
            }
        delete root;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: