-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.c
80 lines (61 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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "trie.h"
#define N 8
TrieNode* readFile(TrieNode *root, char *path) {
FILE *file;
char word[26];
if ((file = fopen(path, "r")) == NULL) { //anoigw to leksiko
perror("source-file not found");
return;
}
while(fgets(word, 25, file) != NULL) { //gia kathe leksi pou diavazw
root = addToTrie(root, word); //prosthetw ti leksi sto trie
}
fclose(file);
return root;
}
/*************************************************************/
/*I ulopoiisi tis eisagwgis sto trie vasistike stin perigrafi*/
/*sto site auto*/
/* http://fathimashadiyya.wordpress.com/2011/10/13/trie-data-structure-and-implementation-of-auto-complete/ */
/*simfwna me tin opoia epilegw se poio keli-paidi tou komvou/pinaka tha paw*/
/*me vasi ton kwdiko ascii tou xaraktira*/
/*************************************************************/
TrieNode* addToTrie(TrieNode *root, char* word) {
int i, j, cell, length;
if (root == NULL)
root = malloc(sizeof(TrieNode));
length = strlen(word);
TrieNode *temp_root;
LeafNode *temp;
temp_root = root; //save the root node to return it
for (i=0 ; i<length - 1 ; i++) { //for every character
cell = word[i] % 'a'; //i will allocate memory for child node
if (root->child[cell] == NULL) { //if the child node is null
root->child[cell] = malloc(sizeof(TrieNode));
root->child[cell]->value = word[i]; //save the char value
for (j=0 ; j<26 ; j++)
root->child[cell]->child[j] = 0;
root->child[cell]->parent = root; //connect child to its father
}
root = root->child[cell]; //and move on the the child node
}
cell = '@' % 'a';
root->leaf = malloc(sizeof(LeafNode)); //allocate space for the leaf node
root->leaf->counter = 0;
root->leaf->parent = root; //connect the leaf to its father
temp = root->leaf;
while (root != temp_root){ //until i reach the root
for (i=0 ; i<N ; i++) { // i add the leaf in the array of every node-father of the leaf
if (root->leaf_pointer[i] == NULL) { //if there is space
root->leaf_pointer[i] = malloc(sizeof(LeafNode));
root->leaf_pointer[i] = temp;
break;
}
}
root = root->parent;
}
return temp_root;
}