fork download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. struct node{
  5. bool eow;
  6. node* child[26];
  7. };
  8. node *root;
  9. node *createnode()
  10. {
  11.  
  12. node* n=new node;
  13. n->eow=false;
  14. for(int i=0;i<26;i++)
  15. {
  16. n->child[i]=NULL;
  17. }
  18. return n;
  19. }
  20.  
  21. void insertword(string s)
  22. {
  23.  
  24. node *cur=root;
  25. for(int i=0;i<s.size();i++)
  26. {
  27. int j=s[i]-'a';
  28.  
  29. if(cur->child[j]==NULL)
  30. {
  31.  
  32. cur->child[j]=createnode();
  33.  
  34. }
  35.  
  36. cur=cur->child[j];
  37. }
  38. cur->eow=true;
  39. }
  40. void print(node *cur=root, string s="")
  41. {
  42.  
  43. if(cur->eow==true)
  44. {
  45. cout<<s<<endl;
  46. }
  47. for(int i=0;i<26;i++)
  48. {
  49.  
  50. if(cur->child[i]!=NULL)
  51. {
  52. char c=(i+'a');
  53.  
  54. print(cur->child[i],s+c);
  55. }
  56. }
  57. }
  58.  
  59. int main()
  60. {
  61. root=createnode();
  62. insertword("hello");
  63. insertword("hel");
  64. insertword("red");
  65. insertword("green");
  66. insertword("reddy");
  67. print();
  68. //delete node;
  69. }
  70.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
green
hel
hello
red
reddy