二叉排序树(BinarySortTree)的实现


/*
    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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值