-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.c
114 lines (98 loc) · 2.27 KB
/
trie.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "header.h"
// This function calculates the index of the trie tree where a particular node must be inserted
int CHAR_TO_INDEX(char c){
return ((int)c - (int)'a');
}
//Seaches for a string key in the trie tree with root as *root
int search(struct TrieNode *root, const char *key)
{
int level;
int length = strlen(key);
int index;
struct TrieNode *pCrawl = root;
for (level = 0; level < length; level++)
{
index = CHAR_TO_INDEX(key[level]);
if (!pCrawl->children[index])
return 0;
pCrawl = pCrawl->children[index];
}
return (pCrawl != NULL && pCrawl->isEndOfWord);
}
//Checks if a particular node is the leaf node by checking for the isEndOfWord bit
int isLeafNode(struct TrieNode* root)
{
if(root->isEndOfWord){
return 1;
}
return 0;
}
//A recursive function to display the contents of the trie
void display(struct TrieNode* root, char str[], int level)
{
if (isLeafNode(root))
{
str[level] = '\0';
printf("%s\n",str);
}
int i;
for (i = 0; i < 26; i++)
{
if (root->children[i])
{
str[level] = i + 'a';
display(root->children[i], str, level + 1);
}
}
}
// Returns new trie node (initialized to NULLs)
struct TrieNode *getNode(void)
{
struct TrieNode *pNode = NULL;
pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode));
if (pNode)
{
int i;
pNode->isEndOfWord = 0;
for (i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
}
return pNode;
}
void form_trie_tree(char* filename, struct TrieNode *root)
{
FILE * fp = fopen(filename, "r");
if (fp == NULL) return ;
char c;
int end=0;
int count = 0;
int index;
while((c = fgetc(fp)) != EOF)
{
struct TrieNode *pCrawl = root;
while(c!= ' ' && c!= '\n'){
if(isupper(c))
c = tolower(c);
index = CHAR_TO_INDEX(c);
if(index<0){
break;
}
if(!pCrawl->children[index])
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
c = fgetc(fp);
if(c==EOF){
end=1;
break;
}
}
pCrawl->isEndOfWord = 1;
if(end)
break;
}
fclose(fp);
}