学习笔记 二叉搜索树(BST)

来源:互联网 发布:360浏览器注入js 编辑:程序博客网 时间:2024/05/23 10:43

基于二叉树模板类可以定义二叉搜索树。

一颗普通的二叉树可以称为列表中的列表结构。因此,在列表结构中查找操作时间复杂度线性正比于列表的长度。对树这种半线性结构也线性正比于树高,也就是O(n)的时间,而向量结构中的二分查找则可以在O(logn)的时间内,完成查找。但是静态存储执行插入和删除操作会达到O(n)的时间。综合,向量与列表的优点,构造一个新型的数据结构。

由循秩访问到循链接访问到循关键码访问。

template<typename k,typename v>struct Entry{    K key;V value;    //默认构造函数    Entry(K k=K(),V v=V()):    key(k),value(v){}    //基于克隆的构造函数    Entry(Entre<K,V> const& e)():    key(e.key),value(e.value){}    bool operator< (Entry<K,V> const& e){return key<e.key}    ...需要时自己重载} 
//BST模板类#include "BinTree.h"template<typename T>class BST : public BinTree<T>{//由二叉树模板派生而来protected:    BinNodePosi(T) _hot;public:    virtual BinNodePosi(T) insert(const T& e);    //注意 查找接口返回的是BinTree<T>*&    virtual BinNodePosi(T) & Search(const T& e);    virtual bool remove(const T& e);    //3+4重构    BinNodePosi(T) connect34(BinNodePosi(T) a,BinNodePosi(T) b,BinNodePosi(T) c    BinNodePosi(T) T0,BinNodePosi(T) T1,BinNodePosi(T) T2,BinNodePosi(T) T3);    BinNodePosi(T) rotateAt(BinNodePosi(T) x);}

查找算法的实现,采用减而治知的策略,实现二分查找树结构版。

template<typename T>static BinNodePosi(T) & SearchIn(BinNodePosi(T) &v,const T& e,BinNodePosi(T) &_hot){    /*处理递归基。    *如果遇到v不存在或者直接命中,返回即可。    *而如果没有遇到,将v交给_hot。    */    if(!v||e==v->data)  return v;    _hot=v;    if(e<v->data) return SearchIn(v->lc,e,_hot);//深入左子树    else return SearchIn(v->rc,e,_hot);//深入右子树}也就是说,不论是查找成功或是失败,_hot都将返回“命中节点”的父亲。template<typename T>BinNodePosi(T) & Search(BinNodePosi(T) &v,const T& e,BinNodePosi(T) &_hot){    return SearchIn(_root,e,_hot=NULL);}

就复杂度而言,最坏只不过树高而已。

插入算法

template<typename T>BinNodePosi(T) insert(const T& e){    BinNodePosi(T) &x = Search(e);    if(x) return x;    else{        x = new BinNode<T>(e,_hot);        _size++;        updateHeightAbove(x);        return x;    }}
原创粉丝点击