字典樹(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;
}
点赞