字典树(trie)

 

#include<iostream>
#include<vector>
#include<string>
using namespace std;

#define MAXSIZE 10

typedef struct trie
{
	char *data;
	struct trie *next[26];
    trie():data(NULL)
	{
		for(int k=0;k<26;k++)
			next[k]=NULL;
	}
}TRIE;

TRIE *trie;

void print(TRIE *root)
{   
	if(!root) return;
	if(root->data!=NULL) cout<<root->data<<endl;
	for(int i=0;i<26;i++)
		print(root->next[i]);
}

void free_node(TRIE *root)
{
  if(root==NULL) return;
  for(int i=0;i<26;i++)
  {
	  trie=root->next[i];
	  free_node(trie); 
      if(trie!=NULL&&trie->data!=NULL)
	  {	
	  delete trie->data;
      trie=NULL;
	  }
  }
}

void free_trie(TRIE *root)
{
  free_node(root);
  if(root->data!=NULL) delete root->data;
}

void insert(TRIE * &root,char *str,const char *data)
{
   if(!root) return;
   TRIE *trie = root;
   char *cur=str;
   int i;
   while(*cur)
   {   
      if(*cur>='A'&&*cur<='Z') i=*cur-'A';
	  else if(*cur>='a'&&*cur<='z') i=*cur-'a';
	  if(!trie->next[i]) 
	  {
		  trie->next[i]=new TRIE();
	  }
      cur++;
	  trie=trie->next[i];
   }
   trie->data=new char(strlen(data)+1);
   strcpy(trie->data,data);
}

int search(TRIE *root,char *str,char *result)
{
  char *cur=str;
  int i,j;
  while(*cur)
  {
      if(*cur>='A'&&*cur<='Z') i=*cur-'A';
	  else if(*cur>='a'&&*cur<='z') i=*cur-'a';
	  if(root->next[i]==NULL) 
	  {
		  strcpy(result,"");
		  return 0;
	  }
	  cur++;
	  root=root->next[i];
  }
  strcpy(result,root->data);
  return 1;
}

int main()
{   
    TRIE *root;
	root=new TRIE();
	insert(root,"Alexander-china","this is Alexander-china!");
	insert(root,"zhang san","this is zhang san!");
	insert(root,"li si","this is li si!");
//	print(root);
	char result[200];
	search(root,"Alexander-china",result);
	cout<<result<<endl;
	search(root,"zhang san",result);
	cout<<result<<endl;
	search(root,"li si",result);
	cout<<result<<endl;
    free_trie(root);
	system("pause");
	return 1;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值