您的位置:首页 > 其它

HDU-3791二叉搜索树

2013-06-20 21:54 281 查看
#include<iostream>
#include<string>
#include<fstream>
int n;
std::string str;
std::string str1,str2,strcmp1,strcmp2;
class btree
{
struct node
{
node():v(0),left(NULL),right(NULL){}
int v;
node* left;
node* right;
};
private:
node* root_;
public:

btree()
{
root_=NULL;
}
void insert(int v)
{
insert(v,root_);
}
void print()
{
print_1(root_);
print_2(root_);
}
void clear()
{
clear(root_);
root_=NULL;
}
private:
void insert(int& v,node *& n)
{
if(n==NULL){
n=new node();
n->v=v;
return;
}
if(v<=n->v){
insert(v,n->left);
}else{
insert(v,n->right);
}
}
void print_1(node* n)
{
if(n==NULL){
return;
}
strcmp1.append(1,'0'+n->v);
print_1(n->left);
print_1(n->right);
}
void  print_2(node* n)
{
if(n==NULL){
return;
}
print_2(n->left);
strcmp2.append(1,'0'+n->v);
print_2(n->right);
}
void clear(node* n)
{
if(n==NULL){
return ;
}
clear(n->left);
clear(n->right);
delete(n);
n=NULL;
}
};

btree tree;
void build(std::string &str)
{
for(int i=0;i!=str.size();i++){
tree.insert(str[i]-'0');
}
tree.print();
tree.clear();
}
int main()
{
//std::fstream std::cin("1.txt");
while (std::cin>>n&&n){
std::cin>>str;
build(str);
str1.assign(strcmp1);
str2.assign(strcmp2);
strcmp1.clear();
strcmp2.clear();
for(int i=0;i!=n;i++){
std::cin>>str;
build(str);
if(str1==strcmp1&&str2==strcmp2){
std::cout<<"YES"<<std::endl;
}else{
std::cout<<"NO"<<std::endl;
}
strcmp1.clear();
strcmp2.clear();
}

str.clear();
str1.clear();
str2.clear();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: