Advertisement
Guest User

TRIE

a guest
Oct 15th, 2019
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define alphabet_size 26
  5.  
  6. struct TrieNode {
  7. TrieNode* alphabet[26];
  8. bool isLeaf;
  9. TrieNode(){
  10. for(int i=0;i<26;i++){
  11. alphabet[i]=NULL;
  12. }
  13. isLeaf = false;
  14. }
  15.  
  16. };
  17.  
  18. class TRIE {
  19. TrieNode* root;
  20. void delNodes(TrieNode* cur);
  21. public:
  22. TRIE();
  23. ~TRIE();
  24. TRIE(bool h);
  25. void insert(string word);
  26. bool search(string word);
  27. };
  28.  
  29. TRIE::TRIE(){
  30. root = new TrieNode();
  31. }
  32.  
  33. void TRIE::delNodes(TrieNode *cur){
  34. for(int i=0;i<alphabet_size;i++){
  35. if(cur->alphabet[i]!=NULL){
  36. delNodes(cur->alphabet[i]);
  37. }
  38. }
  39. delete(cur);
  40. }
  41.  
  42. TRIE::~TRIE(){
  43. TrieNode *cur = root;
  44. delNodes(cur);
  45. }
  46.  
  47.  
  48. TRIE::TRIE(bool h){
  49. root = new TrieNode();
  50. }
  51.  
  52. void TRIE::insert(string word){
  53. TrieNode *cur = root;
  54. for(int i=0;i<word.size();i++){
  55. int ch = word[i]-'a';
  56. if(cur->alphabet[ch]==NULL){
  57. cur->alphabet[ch] = new TrieNode();
  58. }
  59. cur = cur->alphabet[ch];
  60. }
  61. cur->isLeaf = true;
  62. }
  63.  
  64.  
  65. bool TRIE::search(string word){
  66. TrieNode *cur = root;
  67. for(int i=0;i<word.size();i++){
  68. int ch = word[i]-'a';
  69. if(cur->alphabet[ch]==NULL){
  70. return false;
  71. }
  72. cur = cur->alphabet[ch];
  73. }
  74. return (cur->isLeaf == true);
  75. }
  76.  
  77.  
  78.  
  79.  
  80. int main(){
  81. TRIE trie(true);
  82. trie.insert("hello");
  83. trie.insert("hel");
  84. trie.insert("how");
  85.  
  86. cout<<trie.search("he")<<endl;
  87. cout<<trie.search("hello")<<endl;
  88. cout<<trie.search("she")<<endl;
  89. return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement