trie 树举例

来源:互联网 发布:搜狗输入法 ubuntu 编辑:程序博客网 时间:2024/05/29 18:55
 

#define WORDS_END_TAG 0x20
typedef struct Node{
 wchar word;
 Node *p_lefson;  //左儿子
 Node *p_rightbrother; //右兄弟

}*pCnNode,CnNode;
typedef struct treenode{
 wchar Cn_CUW[CUW_COUNT];   //chinese commonly used word
 pCnNode CnNodeRoot[CUW_COUNT];
 unsigned short CnCuwCount;
}CnTree,*pCnTree;
pCnTree CnTrie;
short tree_create_helper2(pCnNode root, wchar *word)
{
 if(root == 0 && root->word != *word) return ;
 wchar *p = word;
 pCnNode node = root;
 while(*p)
 {
  if(*p == node->word){  //指向本节点
   if(node->p_lefson == 0)
    node->p_lefson = (pCnNode)calloc(1,sizeof(CnNode));
   node = node->p_lefson;
  }
  else if(node->word == 0){
   node->word = *p;
   if(node->p_lefson == 0) node->p_lefson = (pCnNode)calloc(1,sizeof(CnNode));
   node = node->p_lefson;
  }
  else{
   pCnNode p_rightbrother;
   if(node->p_rightbrother == 0)
    node->p_rightbrother = (pCnNode)calloc(1,sizeof(CnNode));
   p_rightbrother = node->p_rightbrother;

   while(p_rightbrother->word != 0 && p_rightbrother->p_rightbrother != 0 && p_rightbrother->word != *p)
    p_rightbrother = p_rightbrother->p_rightbrother;
   if(p_rightbrother->word == 0 ) p_rightbrother->word = *p;
   else if(p_rightbrother->p_rightbrother == 0 && p_rightbrother->word != *p){
    p_rightbrother->p_rightbrother = (pCnNode)calloc(1,sizeof(CnNode));
    p_rightbrother = p_rightbrother->p_rightbrother;
    p_rightbrother->word = *p;
   }

   if(p_rightbrother->p_lefson == 0)
    p_rightbrother->p_lefson = (pCnNode)calloc(1,sizeof(CnNode));
   node = p_rightbrother->p_lefson;
  }

 p++;
 
 }

 if(node->word != 0 && node->word != WORDS_END_TAG){
  while(node->word != WORDS_END_TAG && node->p_rightbrother != 0)
   node = node->p_rightbrother;
  if(node->p_rightbrother == 0 && node->word != WORDS_END_TAG)
   node->p_rightbrother = (pCnNode)calloc(1,sizeof(CnNode));
   node = node->p_rightbrother;
 }

 node->word = WORDS_END_TAG;

}
short tree_create_helper1(wchar *word)

 wchar *p = word;
 int index = getindex(*p);
 if(CnTrie->CnNodeRoot[index] == 0){
  CnTrie->CnNodeRoot[index] = (CnNode *)calloc(1,sizeof(CnNode));
  CnTrie->CnNodeRoot[index]->word = *p;
 }
 pCnNode node = CnTrie->CnNodeRoot[index];

 tree_create_helper2(node,word);

}


short tree_create(const char * toks_fname, const char * cis_fname)
{
 wchar *word;
 tree_create_helper1(word);

}

原创粉丝点击