一个搜索二叉树的类

来源:互联网 发布:webex软件下载 编辑:程序博客网 时间:2024/06/07 11:53
 #include <iostream>
 #include<cstdlib>
 #include<ctime>
using namespace std;
class BinarySearchTree;
class BinaryNode
{
public :
  int element;
  BinaryNode *leftChild;
  BinaryNode *rightChild;
  BinaryNode(int theElement,BinaryNode *lt,BinaryNode *rt)
  :element(theElement),leftChild(lt),rightChild(rt){};
  friend class BinarySearchTree;
};
class BinarySearchTree  //搜索树的类,不存储树,只提供操作
{ public:
    BinaryNode *root;
    BinarySearchTree(BinaryNode *rt){root=rt;}
    
    BinaryNode* findMax(BinaryNode *t)const;
    BinaryNode* findMin(BinaryNode *t)const;
    BinaryNode* find(int x,BinaryNode * t)const;

void insert(int x,BinaryNode * & t);
void remove(int x,BinaryNode * & t);
void removeMin(BinaryNode * & t);
};
BinaryNode* BinarySearchTree::find(int x,BinaryNode* t)const
{
  while(t!=NULL)
  { if(t->element==x) return t; //自己加的
    if(x<t->element) t=t->leftChild;
else if(x>t->element) t=t->rightChild;
  }
  return NULL;
}
BinaryNode *BinarySearchTree::findMax(BinaryNode* t)const
{ if(t!=NULL)
    while(t->rightChild!=NULL) t=t->rightChild;
  return t;
}
BinaryNode *BinarySearchTree::findMin(BinaryNode* t)const
{ if(t!=NULL)
    while(t->leftChild!=NULL) t=t->leftChild;
  return t;  
}
void BinarySearchTree::insert(int x,BinaryNode* &t)
{ if(t==NULL)
   t=new BinaryNode(x,NULL,NULL);
  else if(x<t->element) insert(x,t->leftChild);
       else insert(x,t->rightChild);//允许重复
}
void BinarySearchTree::removeMin(BinaryNode* &t)
{ if(t==NULL)
   { cout<<"ERROR";
     return;
   }
  else{  if(t->leftChild!=NULL)
           removeMin(t->leftChild);
else{ if(t->leftChild==NULL)
      { BinaryNode* tmp;
tmp=t;
t=t->rightChild;
delete tmp;
}
    }
      }
}
void BinarySearchTree::remove(int x,BinaryNode* &t)
{  if(t==NULL) {cout<<"ERROR";return;}
   if(x<t->element)remove(t->element,t->leftChild);
   else if(x>t->element) remove(t->element,t->rightChild);
       else{ if(t->leftChild!=NULL && t->rightChild!=NULL)
                 { t->element=findMin(t->rightChild)->element;
                    removeMin(t->rightChild);
                }
                else{ BinaryNode* tmp=t;
                             t=(t->leftChild!=NULL)?t->leftChild:t->rightChild;
                          delete tmp;
                        }
            }
}
void viewTree(BinaryNode* t)//
{  if(t==NULL)  return;
    else{  if(t->leftChild!=NULL) viewTree(t->leftChild);
                cout<<t->element<<" ";
                if(t->rightChild!=NULL) viewTree(t->rightChild);
                
           }
}
int main()
{  int n;
    cin>>n;
    srand((unsigned)time(0));
    BinarySearchTree bst(NULL);
    BinaryNode* r=NULL;
    for(int i=1;i<=n;i++)
    { int a=rand()%32000;
       cout<<i<<"   "<<a<<"insert"<<endl;    
        bst.insert(a,r);
    }
    viewTree(r);
    
    
        
}
0 0