TST.h
#pragma once
#include <memory>
#include <string>
class TST
{
private:
class Node
{
private:
std::unique_ptr<int> c;
bool end;
std::unique_ptr<Node> left;
std::unique_ptr<Node> mid;
std::unique_ptr<Node> right;
private:
void put(const std::string& s, const int& pos)
{
if (pos == s.length())
return;
if (c == nullptr)
{
c = std::move(std::unique_ptr<int>(new int(s[pos])));
if (pos == s.length() - 1)
{
end = true;
return;
}
if (mid == nullptr)
mid = std::move(std::unique_ptr<Node>(new Node));
mid->put(s, pos + 1);
return;
}
int temp = *c;
if (s[pos] < temp)
{
if (left == nullptr)
left = std::move(std::unique_ptr<Node>(new Node));
left->put(s, pos);
}
else if (s[pos] > temp)
{
if (right == nullptr)
right = std::move(std::unique_ptr<Node>(new Node));
right->put(s, pos);
}
else
{
if (mid == nullptr)
mid = std::move(std::unique_ptr<Node>(new Node));
mid->put(s, pos);
}
}
bool find(const std::string& s, const int& pos)
{
if (pos >= s.length())
return false;
if (c == nullptr)
return false;
if (end == true && pos == s.length() - 1 && *c == s[pos])
return true;
else if (end != true && pos == s.length() - 1 && *c == s[pos] && mid != nullptr)
return mid->find(s, pos);
else
{
int temp = *c;
if (s[pos] < temp && left != nullptr)
return left->find(s, pos);
else if (s[pos] > temp && right != nullptr)
return right->find(s, pos);
else if (s[pos] == temp && mid != nullptr)
return mid->find(s, pos + 1);
}
return false;
}
public:
Node()
:c(nullptr),left(nullptr),mid(nullptr),right(nullptr),end(false)
{
}
void put(const std::string& s)
{
put(s, 0);
}
bool find(const std::string& s)
{
return find(s, 0);
}
};
private:
std::unique_ptr<Node> root;
public:
TST():root(new Node)
{
}
public:
void put(const std::string& s)
{
root->put(s);
}
bool find(const std::string& s)
{
return root->find(s);
}
};
main.cpp
#include <iostream>
#include "TST.h"
using namespace std;
int main()
{
TST t;
t.put("marco");
t.put("wh");
t.put("marcom");
t.put("misst");
t.put("网红");
t.put("帅哥");
t.put("帅把");
cout << boolalpha << t.find("帅哥") << endl;
cout << t.find("辣妹") << endl;
cout << t.find("网红") << endl;
cout << t.find("marco") << endl;
system("pause");
return 0;
}