-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie_Basics.C
137 lines (110 loc) · 2.04 KB
/
Trie_Basics.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct Trie{
char data;
struct Trie* next[26];
};
typedef struct Trie TNode;
TNode* GetNode(){
TNode* newNode=(TNode*)malloc(sizeof(TNode));
if(newNode){
newNode->data=0;
int i;
for(i=0;i<26;i++){
newNode->next[i]=NULL;
}
}else{
printf("\nMemory Error");
}
return newNode;
}
void InsertTrie(TNode** root,char* word){
int length=strlen(word);
int i;
int index;
if(!(*root)){
(*root)=GetNode();
//printf("\nHere");
}
TNode* tmpNode=(*root);
for(i=0;i<length;i++){
index=word[i]-97;
if(tmpNode->next[index]==NULL){
//printf("\nReaching here ");
tmpNode->next[index]=GetNode();
}
tmpNode=tmpNode->next[index];
}
tmpNode->data=1;
}
int SearchTrie(TNode* root,char* word){
if(!root){
return 0;
}
int length=strlen(word);
int i;
int index;
TNode* tmpNode=root;
for(i=0;i<length;i++){
index=word[i]-97;
if(tmpNode->next[index]==NULL){
return 0;
}
tmpNode=tmpNode->next[index];
}
return tmpNode->data==1 && tmpNode;
}
void PrintCurrent(char* buffer,int index){
int i;
for(i=0;i<index;i++){
printf("%c",buffer[i]);
}
printf("\n");
}
void PrintAll(TNode* root,char* buffer,int index){
if(!root){
return;
}
int i;
if(root->data==1){
PrintCurrent(buffer,index);
}
for(i=0;i<26;i++){
if(root->next[i]){
buffer[index]=97+i;
PrintAll(root->next[i],buffer,index+1);
}
}
}
int main(){
int n;
printf("\nEnter the number of strings you want to add: ");
scanf("%d",&n);
int i;
char data[100];
TNode* root=NULL;
for(i=0;i<n;i++){
//printf("\nEnter the length of string you want to add : ");
printf("\nEnter the string you want to add : ");
scanf("%s",data);
InsertTrie(&root,data);
}
printf("\%d words added ",n);
getch();
printf("\nEnter the string you want to search : ");
scanf("%s",data);
int result=SearchTrie(root,data);
if(result){
printf("\nWord found !Hurray!");
}else{
printf("\nSorry! word not found !");
}
char* buffer=(char*)malloc(sizeof(char)*100);
printf("\nPress enter to print all the words in the dictionary you just created :\n");
getch();
PrintAll(root,buffer,0);
getch();
return 0;
}