64,682
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <cctype>
#include <string>
#include <cstdio>
using namespace std;
class node
{
public:
node(string str = "") :word(str), left(NULL), right(NULL), count(1)
{
}
string word;
node *left;
node *right;
int count;
};
class BSTree
{
public:
BSTree() :root(NULL)
{
}
node *find(const string&, node *&);
void insert(const string &);
void del(const string &);
void search(const string &str);
void print(node *);
void printTree()
{
print(root);
}
private:
node *root;
};
void BSTree::search(const string &str)
{
node *pp, *p;
p = find(str, pp);
if (!p)
{
printf("-1\n");
}
else
{
printf("%s %d\n", p->word.c_str(), p->count);
}
}
node *BSTree::find(const string &str, node *&parent)
{
node *p = root;
while (p && (str != p->word))
{
parent = p;
if (str < p->word)
{
p = p->left;
}
else if (str>p->word)
{
p = p->right;
}
}
return p;
}
void BSTree::insert(const string &str)
{
node *pp = NULL, *p;
if ((p = find(str, pp)) != NULL)
{
p->count += 1;
return;
}
node *r = new node(str);
if (!root)
{
root = r;
}
else if (str < pp->word)
{
pp->left = r;
}
else
{
pp->right = r;
}
}
void BSTree::del(const string &str)
{
node *p = NULL, *pp = NULL;
if ((p = find(str, pp)) == NULL)
{
return;
}
if (p->left && p->right)
{
node *s = p->right, *ps = p;
while (s->left)
{
ps = s;
s = s->left;
}
p->word = s->word;
p->count = s->count;
p = s;
pp = ps;
}
node *pc;
if (p->left)
{
pc = p->left;
}
else
{
pc = p->right;
}
if (p == root)
{
root = pc;
}
else
{
if (p == pp->left)
{
pp->left = pc;
}
else
{
pp->right = pc;
}
}
delete p;
}
void BSTree::print(node *h)
{
if (!h)
{
return;
}
print(h->left);
printf("%s %d\n", h->word.c_str(), h->count);
print(h->right);
}
string convert(const string &str)
{
string s;
for (int i = 0; i < str.length(); ++i)
{
if (isalpha(str[i]))
{
if (isupper(str[i]))
{
s.push_back(tolower(str[i]));
}
else
{
s.push_back(str[i]);
}
}
}
return s;
}
int main()
{
BSTree tree;
string s;
char c;
while ((c = cin.get()) != 'X')
{
cin.get();
switch (c)
{
case 'T':
getline(cin, s, ' ');
while (s != "@")
{
tree.insert(convert(s));
getline(cin, s, ' ');
}
break;
case 'S':
getline(cin, s, ' ');
while (s != "#")
{
tree.del(convert(s));
getline(cin, s, ' ');
}
break;
case 'V':
tree.printTree();
break;
case 'Q':
getline(cin, s, ' ');
while (s != "#")
{
tree.search(convert(s));
getline(cin, s, ' ');
}
break;
}
}
return 0;
}