fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<limits.h>
  5. #include<math.h>
  6. #include<string.h>
  7. #include<stdbool.h>
  8.  
  9. typedef long long ll ;
  10.  
  11. // trie dictionnary
  12.  
  13. typedef struct Trienode{
  14. char letter;
  15. bool isword;
  16. struct Trienode *children[26];
  17. }Trienode;
  18.  
  19. Trienode *createTrienode(char c){
  20. Trienode *to = (Trienode *)malloc(sizeof(Trienode));
  21. to->letter=c;
  22. to->isword=false;
  23. for(int i=0;i<26;i++){
  24. to->children[i]=NULL;
  25. }
  26. return to;
  27. }
  28.  
  29. //1
  30. Trienode *insertword(Trienode *root,char *word){
  31. if(!root) root=createTrienode('\0');
  32. if(!*word) return root;
  33. char *ptr =word ;
  34. Trienode *temp=root;
  35. while(*ptr){
  36. if(!temp->children[*ptr-'a']) temp->children[*ptr-'a']=createTrienode(*ptr);
  37. temp=temp->children[*ptr-'a'];
  38. ptr++;
  39. }
  40. temp->isword=true;
  41. return root;
  42. }
  43.  
  44. //2
  45. bool search(Trienode *root , char *word){
  46. if(!root) return false;
  47. Trienode *temp=root;
  48. char *ptr = word;
  49. while(*ptr){
  50. if(!temp->children[*ptr-'a']) return false;
  51. temp=temp->children[*ptr-'a'];
  52. ptr++;
  53. }
  54. return temp->isword;
  55. }
  56.  
  57. //3
  58. void dfs(Trienode *root,char *buffer,char *prefix,int depth){
  59. if(!root) return;
  60. if(root->isword){
  61. buffer[depth]='\0';
  62. if(strncmp(buffer,prefix,strlen(prefix))==0)
  63. printf("%s\n",buffer);
  64. }
  65. for(int i=0;i<26;++i){
  66. if(root->children[i]){
  67. buffer[depth]='a'+i;
  68. dfs(root->children[i],buffer,prefix,depth+1);
  69. }
  70. }
  71. }
  72.  
  73. void show_all_words(Trienode *root,char *prefix){
  74. char buffer[100];
  75. dfs(root,buffer,prefix,0);
  76. }
  77.  
  78. int main() {
  79. Trienode *root = NULL;
  80.  
  81. // Insert words
  82. root = insertword(root, "all");
  83. root = insertword(root, "ally");
  84. root = insertword(root, "bat");
  85. root = insertword(root, "bath");
  86. root = insertword(root, "ball");
  87. root = insertword(root, "mehdi");
  88. root = insertword(root, "mehdiisthebest");
  89.  
  90. printf("Words in trie:\n");
  91. show_all_words(root,"ba");
  92.  
  93. return 0;
  94. }
  95.  
  96.  
  97.  
  98.  
  99.  
Success #stdin #stdout 0.01s 5312KB
stdin
Standard input is empty
stdout
Words in trie:
ball
bat
bath