1+ // C++ implementation of search and insert
2+ // operations on Trie
3+ #include < bits/stdc++.h>
4+ using namespace std ;
5+
6+ const int ALPHABET_SIZE = 26 ;
7+
8+ // trie node
9+ struct TrieNode
10+ {
11+ struct TrieNode *children[ALPHABET_SIZE];
12+
13+ // isEndOfWord is true if the node represents
14+ // end of a word
15+ bool isEndOfWord;
16+ };
17+
18+ // Returns new trie node (initialized to NULLs)
19+ struct TrieNode *getNode (void )
20+ {
21+ struct TrieNode *pNode = new TrieNode;
22+
23+ pNode->isEndOfWord = false ;
24+
25+ for (int i = 0 ; i < ALPHABET_SIZE; i++)
26+ pNode->children [i] = NULL ;
27+
28+ return pNode;
29+ }
30+
31+ // If not present, inserts key into trie
32+ // If the key is prefix of trie node, just
33+ // marks leaf node
34+ void insert (struct TrieNode *root, string key)
35+ {
36+ struct TrieNode *pCrawl = root;
37+
38+ for (int i = 0 ; i < key.length (); i++)
39+ {
40+ int index = key[i] - ' a' ;
41+ if (!pCrawl->children [index])
42+ pCrawl->children [index] = getNode ();
43+
44+ pCrawl = pCrawl->children [index];
45+ }
46+
47+ // mark last node as leaf
48+ pCrawl->isEndOfWord = true ;
49+ }
50+
51+ // Returns true if key presents in trie, else
52+ // false
53+ bool search (struct TrieNode *root, string key)
54+ {
55+ struct TrieNode *pCrawl = root;
56+
57+ for (int i = 0 ; i < key.length (); i++)
58+ {
59+ int index = key[i] - ' a' ;
60+ if (!pCrawl->children [index])
61+ return false ;
62+
63+ pCrawl = pCrawl->children [index];
64+ }
65+
66+ return (pCrawl->isEndOfWord );
67+ }
68+
69+ // Driver
70+ int main ()
71+ {
72+ // Input keys (use only 'a' through 'z'
73+ // and lower case)
74+ string keys[] = {" the" , " a" , " there" ,
75+ " answer" , " any" , " by" ,
76+ " bye" , " their" };
77+ int n = sizeof (keys) / sizeof (keys[0 ]);
78+
79+ struct TrieNode *root = getNode ();
80+
81+ // Construct trie
82+ for (int i = 0 ; i < n; i++)
83+ insert (root, keys[i]);
84+
85+ // Search for different keys
86+ search (root, " the" ) ? cout << " Yes\n " : cout << " No\n " ;
87+ search (root, " these" ) ? cout << " Yes\n " : cout << " No\n " ;
88+ return 0 ;
89+ }
0 commit comments