Advertisement
Sanlover

Trie дерево

Jun 28th, 2021
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <iomanip>
  5. using namespace std;
  6.  
  7. struct Node
  8. {
  9.     vector<Node*> children;
  10.     vector<size_t> keys;
  11.     char symbol = '+';
  12. };
  13.  
  14. class TrieTree
  15. {
  16.     Node* root;
  17.     void addMethod(Node* node, const string& word, const size_t& id, const size_t& key)
  18.     {
  19.         if (id >= word.size())
  20.             return;
  21.  
  22.         for (size_t j = 0; j < node->children.size(); j++)
  23.             if (node->children[j]->symbol == word[id])
  24.             {
  25.                 node->children[j]->keys.push_back(key);
  26.                 addMethod(node->children[j], word, id + 1, key);
  27.                 return;
  28.             }
  29.  
  30.         Node* tmp = new Node();
  31.         tmp->keys.push_back(key);
  32.         tmp->symbol = word[id];
  33.  
  34.         node->children.push_back(tmp);
  35.         addMethod(tmp, word, id + 1, key);
  36.     }
  37.  
  38.     void getByKeyMethod(Node* node, string& word, const size_t& key)
  39.     {
  40.        
  41.         for (size_t i = 0; i < node->children.size() ; i++)
  42.         {
  43.             for (size_t j = 0; j < node->children[i]->keys.size(); j++)
  44.             {
  45.                 if (node->children[i]->keys[j] == key)
  46.                 {
  47.                     word += node->children[i]->symbol;
  48.                     getByKeyMethod(node->children[i], word, key);
  49.                     return;
  50.                 }
  51.                
  52.             }
  53.             return;
  54.         }
  55.     }
  56.  
  57. public:
  58.     TrieTree()
  59.     {
  60.         root = new Node;
  61.         root->symbol = '-';
  62.     }
  63.    
  64.     void add(const string& word, const size_t& key)
  65.     {
  66.         Node* it = root;
  67.         addMethod(root, word, 0, key);
  68.     }
  69.  
  70.     string getByKey(const size_t& key)
  71.     {
  72.         string word;
  73.         getByKeyMethod(root, word, key);
  74.         return word;
  75.     }
  76. };
  77.  
  78. int main()
  79. {
  80.     TrieTree a;
  81.     a.add("word", 1);
  82.     a.add("wordm", 2);
  83.     cout << a.getByKey(2);
  84.     return 0;
  85. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement