字典树Trie_Tree

#include<iostream>
#include<string.h>
using namespace std;

struct Trie_Tree
{
    char *str;
    int nFlag;
    Trie_Tree *arr[26];
};

Trie_Tree *CreateNode()
{
    Trie_Tree *temp = new Trie_Tree;
    memset(temp,0,4*28);
    return temp;
}

void Insert_Trie_Tree(Trie_Tree **root,char *str)
{
    if(root == NULL)
    {
        return ;
    }
	//Trie_Tree *temp = (*root);
 //   char *strbak = str;
 //   while((*strbak) != '\0')
 //   {
 //       if(temp->arr[(*strbak)-'a'] == NULL)
 //       {
 //           temp->arr[(*strbak)-'a'] = CreateNode();
 //       }
 //       temp= temp->arr[(*strbak)-'a'];
	//	 strbak++;
 //   }
 //   temp->nFlag = 1;
 //   temp->str = new char [strlen(str)+1];
 //   strcpy(temp->str,str);
    char *strbak = str;
    while((*strbak) != '\0')
    {
        if((*root)->arr[(*strbak)-'a'] == NULL)
        {
            (*root)->arr[(*strbak)-'a'] = CreateNode();
        }
        root = &((*root)->arr[*strbak - 'a']);
		strbak++;
	}
    (*root)->nFlag = 1;
    (*root)->str = new char [strlen(str)+1];
    strcpy((*root)->str,str);
}
void Create_Trie_Tree(Trie_Tree **root,char* arr[],int nLength)
{
    if(root == NULL)
    {
        return ;
    }
    for(int i =0;i<nLength;i++)
    {
        Insert_Trie_Tree(root,arr[i]);
    }
}
void Print_Trie_Tree(Trie_Tree *root)
{
    if(root == NULL)
    {
        return;
    }
    if(root->nFlag == 1)
    {
        cout<<root->str<<" ";
    }
    for(int i=0;i<26;i++)
    {
		Print_Trie_Tree(root->arr[i]);
    }
}
int Find_Trie_Tree(Trie_Tree *root,char *str)
{
	if(root == NULL || str == NULL)
	{
		return 0;
	}
	while ((*str) != '\0')
	{
		if(root->arr[(*str)-'a'] == NULL)
		{
			return 0;
		}
		root = root->arr[(*str)-'a'];
		str++;
	}
	if(root->nFlag == 1)
	{
		return 1;
	}
}
int main()
{
	Trie_Tree *root = CreateNode();
    char *str[5]={"asdasdb","asdasd","fgdfg","ghg","xcvxcv"};
    Create_Trie_Tree(&root,str,5);
    Print_Trie_Tree(root);
	cout<<endl<<Find_Trie_Tree(root,"oooooo");
	cout<<endl<<"-----------------------------------------"<<endl;
	Insert_Trie_Tree(&root,"oooooo");
	Print_Trie_Tree(root);
	cout<<endl<<Find_Trie_Tree(root,"oooooo")<<endl;
	system("pause");
	return 0;
}

你可能感兴趣的:(字典树Trie_Tree)