trie,又称前缀树字典樹,是一种有序,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值

一个保存了 8 个键的 trie 结构,"A", "to", "tea", "ted", "ten", "i", "in", and "inn".

In the example shown, keys are listed in the nodes and values below them. Each complete English word has an arbitrary integer value associated with it. A trie can be seen as adeterministic finite automaton, although the symbol on each edge is often implicit in the order of the branches.

It is not necessary for keys to be explicitly stored in nodes. (In the figure, words are shown only to illustrate how the trie works.)

Though tries are most commonly keyed by character strings, they don't need to be. The same algorithms can easily be adapted to serve similar functions of ordered lists of any construct, e.g., permutations on a list of digits or shapes. In particular, a bitwise trie is keyed on the individual bits making up a short, fixed size of bits such as an integer number or memory address.

A trie can also be used to replace a hash table, over which it has the following advantages:

  • Looking up data in a trie is faster in the worst case, O(m) time (where m is the length of a search string), compared to an imperfect hash table. An imperfect hash table can have key collisions. A key collision is the hash function mapping of different keys to the same position in a hash table. The worst-case lookup speed in an imperfect hash table is O(N) time, but far more typically is O(1), with O(m) time spent evaluating the hash.
  • There are no collisions of different keys in a trie.
  • Buckets in a trie, which are analogous to hash table buckets that store key collisions, are necessary only if a single key is associated with more than one value.
  • There is no need to provide a hash function or to change hash functions as more keys are added to a trie.
  • A trie can provide an alphabetical ordering of the entries by key.

Tries do have some drawbacks as well:

  • Tries can be slower in some cases than hash tables for looking up data, especially if the data is directly accessed on a hard disk drive or some other secondary storage device where the random-access time is high compared to main memory.[5]
  • Some keys, such as floating point numbers, can lead to long chains and prefixes that are not particularly meaningful. Nevertheless a bitwise trie can handle standard IEEE single and double format floating point numbers.
  • Some tries can require more space than a hash table, as memory may be allocated for each character in the search string, rather than a single chunk of memory for the whole entry, as in most hash tables.

Implementation:

 #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h> typedef struct trie trie;
struct trie
{
char key;
trie *next,*children;
}; trie *newnode(char s)
{
trie *t=(trie *)malloc(sizeof(trie));
t->key=s;
t->next=t->children=NULL;
} void insert(trie **t,char *s,int start)
{if(s[start]=='\0')
{
*t=newnode('#');
return;
}
if(*t==NULL)
{
*t=newnode(s[start]);
insert(&(*t)->children,s,start+);
}
if((*t)->key==s[start])
insert(&(*t)->children,s,start+);
else
insert(&(*t)->next,s,start);
} bool search(trie *t ,char *s,int start)
{ if(t==NULL)
return false; if(t->key=='#' && s[start]=='\0')
return true; if(t->key!='#' && s[start]=='\0' || t->key=='#' && s[start]!='\0')
return false; if(t->key==s[start])
return search(t->children,s,start+); else
return search(t->next,s,start); return false;
} /*void push(trie **t ,char *str)
{ int i=0;
for(i=0;i<strlen(str);i++)
insert(t,str[i]);
}*/ main()
{ int i=; trie *t=NULL;
char ch='y';
while(ch=='y')
{
{char str[];
fflush(stdin);
printf("Enter the word ");
gets(str); insert(&t,str,);
}
// push(&t,str);
fflush(stdin);
printf("more y/n ::");
ch=getchar();
} ch='y';
while(ch=='y')
{char str[];
fflush(stdin);
printf("Enter the string you want to search::");
gets(str); fflush(stdin);
if(search(t,str,))
printf("Found");
else
printf("Not Found"); printf("\n more y/n ::");
scanf("%c",&ch); } getch(); }

随机推荐

  1. 一个适用于层级目录结构的makefile模版

    今天写了个层次化的Makefile模版,用来自动化编译项目,这个模版应当包含以下功能: 适用于层次化结构,Makefile主要内容都放在顶层目录下的Makefile.env中,子层Makefile包含 ...

  2. ZigBee安全相关

    ZigBee安全由AES加密算法和CCM操作方式作为安全方案,广泛使用在ZigBee联盟的通信协议中.ZDO层负责安全策略和安全配置的管理. Technorati 标签: ZigBee 安全 2. 配 ...

  3. JS判断客户端是手机还是PC

    function IsPC() { var userAgentInfo = navigator.userAgent; var Agents = ["Android", " ...

  4. 修改ubuntu按下关机键触发的事件

    gsettings set org.gnome.settings-daemon.plugins.power button-power shutdown will change your the beh ...

  5. [Apache] 2.2与2.4版本在设置虚拟域名时的小差别

    Apache服务器配置虚拟步骤: 1.在httpd.conf中将附加配置文件httpd-vhosts.conf包含进来,接着在httpd-vhosts.conf中写入如下配置: #LoadModule ...

  6. Entity Framework 一次加载许多个 Fluent API 映射

    可通过多种方法来指定模型的 Fluent 映射(从类到数据库). 1.直接在 DbContext 类的 OnModel­Creating 方法中进行映射,如下所示: protected overrid ...

  7. c#配置log4net步骤

    1.引入添加log4net.dll引用 2.建立配置文件Log4Net.config(名字自定义).文件内容参考,输出的文件名称可更改 .运行是要放入到相应bin/debug(release) 目录 ...

  8. 集成环境wamp环境下 memcached的安装

    早就听说过memcached,但是一直没实践过.所有今天有时间就搞了一下,哎废了我一上午才搞定!一上午啊,好丢人.特写记录一下 先说一下我遇到的问题:按照别人教程(还有好多)说的,安装后没有任何的错误 ...

  9. db2查看表空间

    select substr(tbsp_name,1,20) as 表空间名称,substr(tbsp_content_type,1,10) as 表空间类型,sum(tbsp_total_size_k ...

  10. Linux /dev 自动创建设备节点

    #include <linux/module.h> #include <linux/module.h> #include <linux/kernel.h> #inc ...