DTL

Trie

Using Trie with DTL

Initializing a Trie

#include "trie.hpp"
#include <iostream>

int main() {
  // Static
  dby::Trie staTrie;

  // Pointer
  dby::Trie* ptrTrie = new dby::Trie();
  delete ptrTrie;

  return 0;
}

Inserting and searching in a Trie

#include "trie.hpp"
#include <iostream>

int main() {
  // Static
  dby::Trie staTrie;
  staTrie.insert("useful");
  std::cout << "use: " << (staTrie.search("use") ? "YES" : "NO"); // NO
  std::cout << "\nuseful: " << (staTrie.search("useful") ? "YES" : "NO"); // YES
  std::cout << "\nuseful23: " << (staTrie.search("usefulness") ? "YES" : "NO"); // NO
  
  // Pointer
  dby::Trie* ptrTrie = new dby::Trie();
  ptrTrie->insert("apple");
  std::cout << "\nSEARCH -> app: " << (ptrTrie->search("app") ? "YES" : "NO"); // NO
  std::cout << "\nSTARTS WITH -> app: " << (ptrTrie->starts_with("app") ? "YES" : "NO"); // YES

  delete ptrTrie;
  return 0;
}

Trie methods

  • insert(std::string word): Inserts the string 'word' into the trie.
  • search(std::string word): Returs true if the string 'word' is in the trie.
  • starts_with(std::string prefix): Returns true if there is a previously inserted string word that has the prefix 'prefix'.