struct TrieNode *fscan(struct TrieNode *root){ char spell[25]; //max size of word is 24 FILE *fp; fp=fopen("database.dat","r"); if(fp!=NULL){ fscanf(fp,"%s",spell); //printf("%s",spell); //printf("\n"); root=trieCreate(); while(spell[24]!=EOF) //read the file word by word until a EOF character { root=insert(root,spell); //insert a word into the trie data structure fscanf(fp,"%s",spell); //printf("%s",spell); //printf("\n"); spell[24]=fgetc(fp); } root=insert(root,spell); fclose(fp); } else printf("database not found"); return root; }
int main() { // Your Trie object will be instantiated and called as such: struct TrieNode* node = trieCreate(); insert(node, "ab"); printf("%d",search(node, "a")); printf("%d",startsWith(node,"a")); // trieFree(node); return 0; }
/** Inserts a word into the trie. */ trie* insert_trie(trie* root, char* word) { if(root==NULL) root=trieCreate(); int length=strlen(word); int level; struct TrieNode*pcrawl=root; for(level=0;level<length;level++) { int index=CHAR_TO_INDEX(word[level]); if(!pcrawl->Child[index]) { pcrawl->Child[index]=getNode(); } pcrawl=pcrawl->Child[index]; } pcrawl->value=1; }
/** Inserts a word into the trie. */ void insert(struct TrieNode* root, char* word) { if (word[0]=='\0') return; if (root==NULL) return; struct TrieNode* curr=root; for (int pos=0; word[pos]!='\0';pos++){ if (curr->next[word[pos]-'a']==NULL){ struct TrieNode* newNode = trieCreate(); newNode->letter = word[pos]; curr->next[word[pos]-'a'] = newNode; } curr = curr->next[word[pos]-'a']; } curr->isLeaf = true; return; }
/** Inserts a word into the trie. */ void insert(TrieNode* root, char* word) { TrieNode *pCrawl = root; count ++; //check if the word is not empty if(word){ int index=0, i =0; //check if the root is not empty if (root){ while( word[i] != '\n'){ index = ( (int) (word[i]) - (int)'a'); if(!pCrawl->children[index]) { pCrawl->children[index] = trieCreate(); pCrawl->children[index]->value = toupper(word[i]); } pCrawl = pCrawl->children[index]; i++; } //Count !=0 tell us that this is the last node;; pCrawl->count = count; } }}
/** Initialize your data structure here. */ struct WordDictionary* wordDictionaryCreate() { struct WordDictionary* dict = (struct WordDictionary*)malloc(sizeof(struct WordDictionary)); dict->root = trieCreate(); return dict; }