首页 > 其他 > 详细

二分搜索树

时间:2020-03-31 12:16:47      阅读:61      评论:0      收藏:0      [点我收藏+]

二分搜索树结构性质,比根节点大的放到右子树,小的放到左子树,相等的去替换,依次递归

template<typename Key,typename Value>
class BST{
private:
    struct Node{
       Key key;
       Value value;
       Node *left;
       Node *right;

       Node(Key key,Value value){
           this->key = key;
           this->value = value;
           this->left = this->right = NULL;
       }
    };
    Node *root;
    int count;

public:
    BST(){
        root=NULL;
        count=0;
    }
    ~BST(){
        //todo
    }
    int size(){
        return count;
    }
    bool isEmpty(){
        return count==0;
    }
    void insert(Key key,Value value){
        root = insert(root,key,value)
    }
private:
    //向以node为根的二叉搜索树中,插入节点(key,value)
    //返回插入新节点后的二叉搜索树的根
    Node* insert(Node *node,Key key,Value value){
        if(node==NULL){
            count ++;
            return new Node(key,value);
        }
        if(key==node->key)
            node->value = value;
        else if(key <node->key)
            node->left = insert(node->left,key,value);
        else
            node->right = insert(node->right,key,value)
        return node;
    }
    
};

 

二分搜索树

原文:https://www.cnblogs.com/Erick-L/p/12602868.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!