Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <string>
- #include <iomanip>
- using namespace std;
- struct Node
- {
- vector<Node*> children;
- vector<size_t> keys;
- char symbol = '+';
- };
- class TrieTree
- {
- Node* root;
- void addMethod(Node* node, const string& word, const size_t& id, const size_t& key)
- {
- if (id >= word.size())
- return;
- for (size_t j = 0; j < node->children.size(); j++)
- if (node->children[j]->symbol == word[id])
- {
- node->children[j]->keys.push_back(key);
- addMethod(node->children[j], word, id + 1, key);
- return;
- }
- Node* tmp = new Node();
- tmp->keys.push_back(key);
- tmp->symbol = word[id];
- node->children.push_back(tmp);
- addMethod(tmp, word, id + 1, key);
- }
- void getByKeyMethod(Node* node, string& word, const size_t& key)
- {
- for (size_t i = 0; i < node->children.size() ; i++)
- {
- for (size_t j = 0; j < node->children[i]->keys.size(); j++)
- {
- if (node->children[i]->keys[j] == key)
- {
- word += node->children[i]->symbol;
- getByKeyMethod(node->children[i], word, key);
- return;
- }
- }
- return;
- }
- }
- public:
- TrieTree()
- {
- root = new Node;
- root->symbol = '-';
- }
- void add(const string& word, const size_t& key)
- {
- Node* it = root;
- addMethod(root, word, 0, key);
- }
- string getByKey(const size_t& key)
- {
- string word;
- getByKeyMethod(root, word, key);
- return word;
- }
- };
- int main()
- {
- TrieTree a;
- a.add("word", 1);
- a.add("wordm", 2);
- cout << a.getByKey(2);
- return 0;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement