用C语言打印trie中的所有单词

时间:2014-03-28 02:01:46

标签: c recursion printing printf trie

我试图在C中打印trie的内容。但是我不是很成功。并且让我在开始时说我们现在正在学校做这件事,这是一个练习。

这就是我的特里的样子:

struct node{
char letter;//holds the letter associated with that node
int count;//its count
struct node* child[26];//each node can have 26 children
};

struct trie{
struct node* root;
}

此打印方法必须遍历此trie并按字母顺序打印单词,并且不应打印计数为0的单词。

我正在考虑递归,这就是我的代码:

void print(node* root){
char buffer[15];//array to store the letters
if(root==NULL){ return;}//if the root is null return
int i;
int index=0; //index for the buffer
int hasAChild=hasChild(root);
if(hasAChild!=0){//the root has children keep on goinf

    for(i=0;i<27;i++){//go thru all the children and if they have children call print                         recursively
       if(hasChild(root->child[i]){
         print(root->child[i]);
         }
       else{
          //if they have no more children add the letter to the buffer
          buffer[index++]=root->child[i]->letter;
        }
          //print the contents in the bufffer
       printf("%s: %d",root->child[i]->count);
  }
}

//用于确定节点是否有子节点的函数,如果是,则返回其编号,如果不是,则返回0

 int hasChild(root)
    {
  if(root==NULL){
        return 0;
       }

 int i;
 int count=0;
 for(i=0;i<27;i++){
       if(root->child[i]!=NULL){
                   count++;
       }
    }
   return count;
}

这就是它的样子

     root
ab'c'defghijklmn'o'pqr's''t'uvwxyz
  'o'           'p'   'o''o'-subtrie-> "contribute", "open", "source"
  'n'           'e'   'u'
  't'           'n'   'r'
  'r'                 'c'-subtrie->"contribute", "to", "open", 
  'i'                     
  'b'
  'u'
  't'
  'e'-subtrie-> "to", "open", "source" 

所以我只想打印出形成的单词,而不是不形成单词的单词。 任何帮助或指导将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

这个怎么样?

struct list
{
  char *word;
  list *next;
};

void getWord(node *node, list *words, char *previous)
{
  int i;
  char *newWord;
  char *tmp;

  if (node == NULL)
  {
     if (previous == NULL)
       return;
     addBloc(words, previous);
  }
  if (node.count == 0)
     return;
  if (previous == NULL)
  {
    previous = malloc(2);
    previous[0] = node.letter;
    previous[1] = '\0';
  }
  else
  {
    tmp = malloc(strlen(previous) + 2);
    strcpy(tmp, previous);
    tmp[strlen(previous)] = node.letter;
    tmp[strlen(previous) + 1] = '\0';
    free(previous);
    previous = tmp;
  }
  for (i = 0; i < 27; i++)
  {
     if (node.child[i] != NULL)
     {
       getWord(node.child[i], words, strdup(previous));
     }
  }
}

待办事项

  • 使用(node,NULL,NULL);
  • 调用getWord
  • 代码函数addBloc,将一个集团添加到链表单词

解释

目的是贯彻所有孩子并建立一个词。然后将单词存储到链表中。

例证

T和C是A的孩子

O是T的孩子

我和你是O的孩子

算法将

   - previous = 'A'

然后调用方法到T

   - previous = 'AT'

然后调用方法到O

   - previous = 'ATO'

然后调用我的方法

  - previous = 'ATOI'
  - STORE 'ATOI'

然后调用U的方法

  - previous = 'ATOU'
  - STORE 'ATOU'

然后调用方法C

 - previous = 'AC'
 - STORE 'AC'