码迷,mamicode.com
首页 > 其他好文 > 详细

Trie树

时间:2016-02-20 17:37:06      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

// 2016_2_20_trietree.cpp : Defines the entry point for the console application.
//

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

#define NUM 26//每个节点都有26个字母,根节点啥也没有

class Node
{
public:
int count;//记录该处字符串个数
Node* char_arr[NUM];//分支
char* current_str;//记录到达此处的路径上的所有字母组成的字符串
Node();
};

class Trie
{
public:
Node* root;
Trie();

void insert(char* str);
void output(Node* &node,char** str,int& count);
};

//程序未考虑delete动态内存
int main()
{
char** str=new char*[12];//真的好想是指针数组啊
str[0]="zbdfasd";
str[1]="zbcfd";
str[2]="zbcdfdasfasf";
str[3]="abcdaf";
str[4]="defdasfa";
str[5]="fedfasfd";
str[6]="dfdfsa";
str[7]="dadfd";
str[8]="dfdfasf";
str[9]="abcfdfa";
str[10]="fbcdfd";
str[11]="abcdaf";

//建立trie树
Trie* trie=new Trie();
for(int i=0;i<12;i++)
trie->insert(str[i]);//插入字符串

int count=0;
trie->output(trie->root,str,count);//输出count

for(int j=0;j<12;j++)
cout<<str[j]<<endl;

return 0;
}

Node::Node()
{
count=0;
for(int i=0;i<NUM;i++)
char_arr[i]=NULL;
current_str=new char[100];
current_str[0]=‘\0‘;
}

Trie::Trie()
{
root=new Node();
}

void Trie::insert(char* str)
{
int i=0;
Node* parent=root;

//将str[i]插入到trie树中
while(str[i] != ‘\0‘)
{
//如果包含str[i]的分支存在,则新建此分支
if(parent->char_arr[str[i]-‘a‘]==NULL)
{
parent->char_arr[str[i]-‘a‘]=new Node();
//将父节点中的字符串添加到当前节点的字符串中
strcat(parent->char_arr[str[i]-‘a‘]->current_str,parent->current_str);

char str_tmp[2];
str_tmp[0]=str[i];
str_tmp[1]=‘\0‘;

//将str[i]添加到当前节点的字符串中
strcat(parent->char_arr[str[i]-‘a‘]->current_str,str_tmp);

parent=parent->char_arr[str[i]-‘a‘];//这里很重要,使用了递归
}
else
{
parent=parent->char_arr[str[i]-‘a‘];//递归
}
i++;
}
parent->count++;
}

void Trie::output(Node* &node,char** str,int& count)//这个&的作用是引用,是别名,修改这个变量,就能修改传参的那个变量
{
if(node != NULL)
{
if(node->count != 0)
{
for(int i=0;i<node->count;i++)
str[count++]=node->current_str;
}
for(int i=0;i<NUM;i++)
{
output(node->char_arr[i],str,count);
}
}
}

Trie树

标签:

原文地址:http://www.cnblogs.com/Study02/p/5203513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!