二叉搜索树的随机化建立方法

二叉搜索树的随机化建立方法
二叉搜索数是一棵二叉树,其中每一个内部节点都有一个相关的关键字,并有负有以下的性质。任意节点的关键字大于(或者等于)该节点左子树的所有关键字,并小于(或者等于)该节点右子树的所有关键字。

#include  < stdlib.h >
#include 
< iostream.h >
static   int  maxKey  =   1000 ;
typedef 
int  Key;
class  Item{
    
private :
        Key keyval;
        
float  info;
    
public :
        Item()
        {keyvalue 
=  maxKey;}
        Key key()
        {
return  keyvalue;}
        
int   null ()
        {
            
return  keyvalue   == maxKey;
        }
        
void  rand()
        {
            keyval 
=   1000 * ::rand() / RAND_MAX;
        }
        
int  scan(istream &   is = cin)
        {
            
return ( is >> keyvalue >> info ) != 0 );
        }
        
void  show(ostream &  os = cout)
        {
            os
<< keyvalue << "   " << info << endl;
        }
};
ostream
&   operator << (ostream  & os,Item  & X)
{
    X.show(os);
    
return  os;
}


template 
< class  Item, class  Key >
class  ST
{
    
private :
        
struct  node
        {
            Item item;
            node 
* l, * r;
            node(Item x)
            {
                item 
=  x;
                l 
=   0 ;
                r 
=   0 ;
            }
        };
        typedef node 
*  link;
        link head;
        
struct  node nullitem;

        
void  insertR(link  & h,Item x)
        {
            
if (h  ==   0 )
            {
                h 
=   new  node(x);
                
return ;
            }
            
if (x.key() < h -> item.key())
            {
                insertR(h
-> l,x);
            }
            
else
            {
                insertR(h
-> r,x);
            }

        }
        Item searchR(link 
& h,Key v)
        {
            
if (h  ==   0 )
                
return  nullitem;
            
if (h -> item.key()  ==  v)
            {
                
return  h -> Item;
            }
            
else   if (h -> item.key() < v)
            {
                searchR(h
-> right,v);
            }
            
else
            {
                searchR(h
-> left,v);
            }

        }

        }
    
public :
        ST(
int )
        {
        }
        
int  count();
        Item search(Key);
        
void  insert(Item);
        
void  remove(Item);
        Item select(
int );
        
void  show(ostream  & );
};

Posted on 2008-06-16 11:26 micheal's tech 阅读(294) 评论(0)   编辑  收藏 引用 所属分类: Algorithm

你可能感兴趣的:(二叉搜索树的随机化建立方法)