GeekforGeeks Trie - 键树简单介绍 - 构造 插入 和 搜索
版权声明:本文作者靖心,靖空间地址:http://blog.csdn.net/kenden23/,未经本作者同意不得转载。
https://blog.csdn.net/kenden23/article/details/24453639
Trie是非常高效的信息检索数据结构, 时间效率会是O(m),当中m是须要搜索的keyword的长度。
缺点就是须要的存储空间大。
Trie的特点:
1. 每一个Trie的节点都由多个分支构成
2. 每一个分支代表可能的keyword的一个字符
3. 须要mark(标志)每一个keyword的最后一个字符为leaf node(叶子节点)
英文字母的节点数据结构能够表演示样例如以下:
struct TrieNode
{
int value; /* Used to mark leaf nodes */
TrieNode *children[ALPHABET_SIZE];
};
插入keyword:
1. keyword的每一个字符都作为独立的trie节点, 注意每一个子节点都是一组指针,指向下一个trie节点。
2 假设输入的keyword是新的,或者是比原有keyword长, 就须要构造新的节点, 并且须要标志它的结束点为叶子节点。
3. 假设keyword比原有的某个keyword短,那么就能够仅仅标志新的叶子节点。
4. keyword的长度决定了trie的深度
搜索keyword:
1. 比較keyword的字符。然后往下一层移动
2. 假设keyword结束,或者没有这个字符在trie中,那么搜索结束。 前者比較最后一个节点是否是叶子节点,假设是表示搜索成功,否则不成功。后者表示搜索不成功。
參考原文:
http://www.geeksforgeeks.org/trie-insert-and-search/
实现程序:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
#define ALPHABET_SIZE (26)
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')
struct TrieNode
{
int value; /* Used to mark leaf nodes */
TrieNode *children[ALPHABET_SIZE];
};
struct TrieT
{
TrieNode *root;
int count;
};
// Returns new trie node (initialized to NULLs)
TrieNode *getNode(void)
{
TrieNode *pNode = NULL;
pNode = (TrieNode *)malloc(sizeof(TrieNode));
if( pNode )
{
int i;
pNode->value = 0;
for(i = 0; i < ALPHABET_SIZE; i++)
{
pNode->children[i] = NULL;
}
}
return pNode;
}
// Initializes trie (root is dummy node)
void initialize(TrieT *pTrie)
{
pTrie->root = getNode();
pTrie->count = 0;
}
// If not present, inserts key into trie
// If the key is prefix of trie node, just marks leaf node
void insert(TrieT *pTrie, char key[])
{
int level = 0;
int length = strlen(key);
int index = 0;
TrieNode *pCrawl;
pTrie->count++;
pCrawl = pTrie->root;
for( level = 0; level < length; level++ )
{
index = CHAR_TO_INDEX(key[level]);
if( !pCrawl->children[index] )
{
pCrawl->children[index] = getNode();
}
pCrawl = pCrawl->children[index];
}
// mark last node as leaf
pCrawl->value = pTrie->count;
}
// Returns non zero, if key presents in trie
int search(TrieT *pTrie, char key[])
{
int level;
int length = strlen(key);
int index;
TrieNode *pCrawl;
pCrawl = pTrie->root;
for( level = 0; level < length; level++ )
{
index = CHAR_TO_INDEX(key[level]);
if( !pCrawl->children[index] )
{
return 0;
}
pCrawl = pCrawl->children[index];
}
return (0 != pCrawl && pCrawl->value);
}
// Driver
int main()
{
// Input keys (use only 'a' through 'z' and lower case)
char keys[][8] = {"the", "a", "there", "answer", "any", "by", "bye", "their"};
TrieT trie;
char output[][32] = {"Not present in trie", "Present in trie"};
initialize(&trie);
// Construct trie
for(int i = 0; i < ARRAY_SIZE(keys); i++)
{
insert(&trie, keys[i]);
}
// Search for different keys
printf("%s --- %s\n", "the", output[search(&trie, "the")] );
printf("%s --- %s\n", "these", output[search(&trie, "these")] );
printf("%s --- %s\n", "their", output[search(&trie, "their")] );
printf("%s --- %s\n", "thaw", output[search(&trie, "thaw")] );
return 0;
}
更新 2014 5 -16
C++写的类,主要是带构造函数和析构函数。能够非常好管理内存,甚至不须要递归地手动释放内存了,析构函数能够自己主动递归调用释放全部Node,这个是C++比C强大的地方之中的一个:
class TrieInsertAndSearch
{
const static int ALPH_SIZE = 26;
struct Node
{
int val;
Node *children[ALPH_SIZE];
explicit Node(int v = 0) : val(v)
{
for (int i = 0; i < ALPH_SIZE; i++)
{
children[i] = nullptr;
}
}
~Node()
{
for (int i = 0; i < ALPH_SIZE; i++)
{
if (children[i]) delete children[i];
children[i] = nullptr;
}
}
};
struct Tree
{
Node *root;
int count;
explicit Tree(int c = 0, Node *r = nullptr) : count(c), root(r){}
~Tree()
{
if (root) delete root;
root = nullptr;
}
};
Tree *pT;
void insert(char key[])
{
int len = strlen(key);
Node *pCrawl = pT->root;
pT->count++;
for (int lv = 0; lv < len; lv++)
{
int id = key[lv] - 'a';
if (!pCrawl->children[id])
{
pCrawl->children[id] = new Node;
}
pCrawl = pCrawl->children[id];
}
pCrawl->val = pT->count;
}
bool search(char key[])
{
int len = strlen(key);
Node *pCrawl = pT->root;
for (int lv = 0; lv < len; lv++)
{
int id = key[lv] - 'a';
if (!pCrawl->children[id]) return false;
pCrawl = pCrawl->children[id];
}
return (pCrawl && pCrawl->val);
}
public:
TrieInsertAndSearch()
{
char keys[][8] = {"the", "a", "there", "answer", "any", "by", "bye", "their"};
pT = new Tree(0, new Node);
int n = sizeof(keys) / sizeof(keys[0]);
for (int i = 0; i < n; i++)
{
insert(keys[i]);
}
// Search for different keys
if (search("the")) printf("the is in Trie\n");
else printf("the is not in Trie\n");
if (search("these")) printf("these is in Trie\n");
else printf("these is not in Trie\n");
if (search("their")) printf("their is in Trie\n");
else printf("their is not in Trie\n");
if (search("thaw")) printf("thaw is in Trie\n");
else printf("thaw is not in Trie\n");
}
~TrieInsertAndSearch()
{
if (pT) delete pT;
pT = nullptr;
}
};GeekforGeeks Trie - 键树简单介绍 - 构造 插入 和 搜索的更多相关文章
- UE4中的AI行为树简单介绍
UE4引擎中可以实现简单AI的方式有很多,行为树是其中比较常用也很实用的AI控制方式,在官网的学习文档中也有最简单的目标跟踪AI操作教程,笔者在这里只作简单介绍. AIController->和 ...
- Trie树的创建、插入、查询的实现
原文:http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=28977986&id=3807947 1.什么是Trie树 Tr ...
- 萌新笔记——C++里创建 Trie字典树(中文词典)(一)(插入、遍历)
萌新做词典第一篇,做得不好,还请指正,谢谢大佬! 写了一个词典,用到了Trie字典树. 写这个词典的目的,一个是为了压缩一些数据,另一个是为了尝试搜索提示,就像在谷歌搜索的时候,打出某个关键字,会提示 ...
- C++里创建 Trie字典树(中文词典)(一)(插入、遍历)
萌新做词典第一篇,做得不好,还请指正,谢谢大佬! 写了一个词典,用到了Trie字典树. 写这个词典的目的,一个是为了压缩一些数据,另一个是为了尝试搜索提示,就像在谷歌搜索的时候,打出某个关键字,会提示 ...
- SQL 数据库 学习 007 通过一个示例简单介绍什么是字段、属性、列、元组、记录、表、主键、外键 (上)
SQL 数据库 学习 007 通过一个示例简单介绍什么是字段.属性.列.元组.记录.表.主键.外键 (上) 我们来介绍一下:数据库是如何存储数据的. 数据库是如何存储数据的 来看一个小例子 scott ...
- BST&AVL&红黑树简单介绍
(BST&AVL&红黑树简单介绍) 前言: 节主要是给出BST,AVL和红黑树的C++代码,方便自己以后的查阅,其代码依旧是data structures and algorithm ...
- 算法设计和数据结构学习_5(BST&AVL&红黑树简单介绍)
前言: 节主要是给出BST,AVL和红黑树的C++代码,方便自己以后的查阅,其代码依旧是data structures and algorithm analysis in c++ (second ed ...
- python利用Trie(前缀树)实现搜索引擎中关键字输入提示(学习Hash Trie和Double-array Trie)
python利用Trie(前缀树)实现搜索引擎中关键字输入提示(学习Hash Trie和Double-array Trie) 主要包括两部分内容:(1)利用python中的dict实现Trie:(2) ...
- 《PHP 5.5从零開始学(视频教学版)》内容简单介绍、文件夹
<PHP 5.5从零開始学(视频教学版)>当当网购买地址: http://product.dangdang.com/23586810.html <PHP 5.5从零開始学(视频教学版 ...
随机推荐
- NativeCode中通过JNI反射调用Java层的代码,以获取IMEI为例
简单说,就是在NativeCode中做一些正常情况下可以在Java code中做的事儿,比如获取IMEI. 这种做法会使得静态分析Java层代码的方法失效. JNIEXPORT jstring JNI ...
- Python 实现指定目录下 删除指定大小的文件
import os, sys from stat import * BIG_FILE_THRESHOLD = 6000L #1000000L dict1 = {} # dict2 = {} # def ...
- 【转载】LR - 细节解析,为什么LR脚本会去访问“脚本中不存在的“资源?
问题描述 同事遇到的一个问题,LR执行性能测试脚本时,总报出错误,无法访问一个图片的地址,但脚本中明明没有对该资源的请求. Action4.c(12): Warning -27796: Failed ...
- A Quick Look at P3P
P3P Made Simple By default, IE will reject cookies coming from 3rd-party contexts. A 3rd-party conte ...
- mybatis like写法
name like concat(concat('%',#{name}),'%') name like concat('%',#{name},'%')
- react-native-router-flux 页面跳转与传值
1.正向跳转假设情景:从Home页跳转到Profile页面,Profile场景的key值为profile 不带参数: Actions.profile 带参数: Actions.profile({'ke ...
- Linux下Nagios的安装与配置(转载)
一.Nagios简介 Nagios是一款开源的电脑系统和网络监视工具,能有效监控Windows.Linux和Unix的主机状态,交换机路由器等网络设置,打印机等.在系统或服务状态异常时发出邮件或短信报 ...
- KingdeeK3-修改单据邮件发送的自定义字段
只需要执行类似下面语句即可: update ICTemplateentry set FVisForBillType = 63,flookupcls=6 where fid ='P01' and fhe ...
- C# 使用UUID生成各种模式方法
UUID简单说明 常见的方式.可以利用数据库也可以利用程序生成,一般来说全球唯一. 优点: 1)简单,代码方便. 2)生成ID性能非常好,基本不会有性能问题. 3)全球唯一,在遇见数据迁移,系统数据合 ...
- SQL 根据表获取字段字符串
SQLSERVER查询单个数据表所有字段名组合成的字符串脚本 --SQLSERVER查询单个数据表所有字段名组合成的字符串脚本 --应用场合: 用于生成SQL查询字符串中select 字段名列表1 f ...