#include<iostream>
#include<stack>
#include<string>
#include<assert.h>
#include<fstream>
using namespace std;
typedef struct TreeNode{
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int t):data(t),left(NULL),right(NULL){}
}TreeNode;
class BST{
private:
TreeNode* root;
public:
BST():root(NULL){}
bool search(int t){
TreeNode* p=root;
while(p){
if(p->data==t)return true;
else if(p->data>t)p=p->left;
else p=p->right;
}
return false;
}
void insert(int t){
TreeNode* p=root,* r=NULL;
while(p){
if(p->data==t)return;
else if(p->data>t){
r=p;
p=p->left;
}else{
r=p;
p=p->right;
}
}
if(r==NULL){
root=new TreeNode(t);
}else{
if(r->data>t){
r->left=new TreeNode(t);
}else{
r->right=new TreeNode(t);
}
}
}
void remove(int t){
root=remove(root,t);
}
void showData(){
stack<TreeNode*> sta;
TreeNode* p=root;
while(p||!sta.empty()){
if(p){
sta.push(p);
p=p->left;
}else{
p=sta.top();
sta.pop();
cout<<p->data<<" ";
p=p->right;
}
}
cout<<endl;
}
private:
TreeNode* remove(TreeNode* p,int t){
if(p==NULL)return NULL;
if(p->data>t){
p->left=remove(p->left,t);
return p;
}
else if(p->data<t){
p->right=remove(p->right,t);
return p;
}
else{
if(p->left==NULL){
TreeNode* tmp=p->right;
delete p;
return tmp;
}if(p->right==NULL){
TreeNode* tmp=p->left;
delete p;
return tmp;
}else{
TreeNode* r=p,*q=p->left;
while(q->right){
r=q;
q=q->right;
}
p->data=q->data;
if(r==p)
r->left=q->left;
else r->right=q->left;
delete q;
return p;
}
}
}
};
class Command{
protected:
BST* executer;
public:
Command():executer(NULL){}
void setExecuter(BST* root){
executer=root;
}
virtual void execute(int t=0)=0;
virtual ~Command(){}
};
class InsertCommand:public Command{
public:
void execute(int t){
assert(executer!=NULL);
executer->insert(t);
}
};
class SearchCommand:public Command{
public:
void execute(int t){
assert(executer!=NULL);
if(executer->search(t))
cout<<"value in BST"<<endl;
else cout<<"value not in BST"<<endl;
}
};
class DeleteCommand:public Command{
public:
void execute(int t){
assert(executer!=NULL);
executer->remove(t);
}
};
class ShowCommand:public Command{
public:
void execute(int t){
assert(executer!=NULL);
executer->showData();
}
};
class CommandFactory{
public:
static Command* getCommand(const string& command){
if(command=="search")
return new SearchCommand();
if(command=="insert")
return new InsertCommand();
if(command=="delete")
return new DeleteCommand();
if(command=="show")
return new ShowCommand();
return NULL;
}
};
int main(void){
BST bst;
//ifstream infile("test.txt");
string command;
int t;
while(cin>>command>>t){
Command* comm=CommandFactory::getCommand(command);
if(comm==NULL){
cout<<"command error"<<endl;
continue;
}
comm->setExecuter(&bst);
comm->execute(t);
delete comm;
}
return 0;
}
简单实现BST以及简单工厂模式进行测试
最新推荐文章于 2022-02-26 18:19:03 发布