TRIE树

本文介绍了一种使用TRIE树实现字典的数据结构方法,包括查找、插入和删除元素的功能,并提供了完整的C++实现代码。

一个能够实现查找元素、增加元素和删除元素三种操作的数据结构称为字典。TRIE树,又称键树,可以用来构造字典,适合所有元素都是由字母和数字标记的情形。下面是TRIE树的一种C++实现:

#include <stdio.h>
#include <iostream>
#include <string.h>

using namespace std;
const int num_chars = 26;

class Trie {
protected:
struct Trie_node {
char* word;
Trie_node* branch[num_chars];
Trie_node();
};
Trie_node* root;

public:
Trie();
int search(const char* word) const;
int insert(const char* word);
int remove(const char* word);

void printall(char *pre, Trie_node *p);
void printpre(char *pre);
};

Trie::Trie():root(NULL)
{
}

Trie::Trie_node::Trie_node()
{
word = NULL;
for (int i=0; i<num_chars; ++i)
branch[i] = NULL;
}

int Trie::search(const char* word) const
{
char char_code;
Trie_node *location = root;

while( location!=NULL && *word!=0 ) {
if (*word>='A' && *word<='Z')
char_code = *word-'A';
else if (*word>='a' && *word<='z')
char_code = *word-'a';
else
return 0;

location = location->branch[char_code];
word++;
}
if ( location != NULL && location->word != NULL ) {
return 1;
} else
return 0;
}

int Trie::insert(const char* word)
{
int result = 1;
if ( root == NULL ) root = new Trie_node;
char char_code;
Trie_node *location = root;

while( location!=NULL && *word!=0) {
if (*word>='A' && *word<='Z')
char_code = *word-'A';
else if (*word>='a' && *word<='z')
char_code = *word-'a';
else
return 0;

if( location->branch[char_code] == NULL )
location->branch[char_code] = new Trie_node;
location = location->branch[char_code];
word++;
}
if (location->word != NULL)
result = 0;
else {
location->word = new char[strlen(word)+1];
strcpy(location->word, word);
}
return result;
}

int Trie::remove(const char* word)
{
int result = 1;
char char_code;
Trie_node *location = root;

while( location!=NULL && *word!=0) {
if (*word>='A' && *word<='Z')
char_code = *word-'A';
else if (*word>='a' && *word<='z')
char_code = *word-'a';
else
return 0;

location = location->branch[char_code];
word++;
}
if (location) {
delete location->word;
location->word = NULL;
} else {
result = 0;
}
return result;
}

void Trie::printall(char *pre, Trie_node *p)
{
if (p->word != NULL) {
cout<<pre<<endl;
}

for (int i=0; i<num_chars; ++i) {
if (p->branch[i] != NULL) {
char ch = 'a' + i;
char *prestr = (char *)malloc(strlen(pre)+2);
sprintf(prestr, "%s%c", pre, ch);
printall(prestr, p->branch[i]);
free(prestr);
}
}
}

void Trie::printpre(char *pre)
{
char char_code;
char *p = pre;
Trie_node *location = root;

while( location!=NULL && *pre!=0 ) {
if (*pre>='A' && *pre<='Z')
char_code = *pre-'A';
else if (*pre>='a' && *pre<='z')
char_code = *pre-'a';
else
return;

location = location->branch[char_code];
pre++;
}

if (location != NULL)
printall(p, location);

return;
}

int main(int argc, char *argv[])
{
Trie t;

t.insert("liu");
t.insert("aigui");
t.insert("liuag");
t.insert("china");
t.insert("trie");

t.remove("aigui");
t.remove("abc");
t.printpre("");

if (t.search(argv[1]))
cout<<argv[1]<<" was found"<<endl;
else
cout<<argv[1]<<" was not found"<<endl;

if (argv[2])
t.printpre(argv[2]);

return 0;
}

(刘爱贵 / Aiguille LIU)

### Trie的实现原理 Trie(又称前缀)是一种多叉结构,主要用于高效地处理字符串集合。其核心思想是通过共享字符串的前缀部分来减少存储空间和加快查找速度。每个节点代表一个字符,而从根节点到某一子节点的路径组成一个字符串,表示该字符串的存在。 Trie的节点通常包含以下两个主要属性: - **isKey**:布尔值,标记该节点是否为某个完整字符串的结尾。 - **children**:一个指针数组,指向该节点的子节点。数组的大小通常取决于字符集的大小(例如,对于英文小写字母来说,大小为26)。 Trie的基本操作包括插入、查找和删除: - **插入操作**:从根节点开始,依次匹配字符串中的每个字符。如果字符不存在,则创建新节点。当整个字符串插入完成后,将最后一个节点的`isKey`标记为`true`。 - **查找操作**:从根节点出发,匹配字符串中的每个字符。如果中途字符无法匹配,则说明字符串不存在;如果所有字符都匹配成功,还需检查最后一个节点的`isKey`标志,以确认是否为完整字符串。 - **删除操作**:首先确认字符串是否存在于Trie中,如果存在,则从字符串的最后一个字符开始逐层回溯删除节点,直到遇到共享前缀的字符为止。 以下是一个简单的Trie实现的Java代码示例: ```java class TrieNode { private boolean isKey; // 是否为关键词结尾 private TrieNode[] children; // 子节点指针 public TrieNode() { this.isKey = false; this.children = new TrieNode[26]; // 假设只包含小写字母 } public boolean containsKey(char ch) { return children[ch - 'a'] != null; } public TrieNode get(char ch) { return children[ch - 'a']; } public void put(char ch, TrieNode node) { children[ch - 'a'] = node; } public void setKey(boolean key) { isKey = key; } public boolean isKey() { return isKey; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // 插入字符串 public void insert(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { char currentChar = word.charAt(i); if (!node.containsKey(currentChar)) { node.put(currentChar, new TrieNode()); } node = node.get(currentChar); } node.setKey(true); } // 查找字符串 public boolean search(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { char currentChar = word.charAt(i); if (!node.containsKey(currentChar)) { return false; } node = node.get(currentChar); } return node != null && node.isKey(); } // 检查前缀是否存在 public boolean startsWith(String prefix) { TrieNode node = root; for (int i = 0; i < prefix.length(); i++) { char currentChar = prefix.charAt(i); if (!node.containsKey(currentChar)) { return false; } node = node.get(currentChar); } return node != null; } } ``` ### Trie的应用场景 Trie因其高效的前缀匹配特性,在多个领域有着广泛的应用,例如: - **搜索引擎的关键词提示**:用户在搜索框输入时,Trie可以快速提供输入前缀匹配的关键词建议,提升用户体验[^3]。 - **拼写检查**:Trie可以用于拼写检查工具中,通过查找输入单词相似的正确拼写来纠正错误。 - **自动补全**:在输入框中,如浏览器地址栏或命令行界面,Trie可以用于自动补全功能,根据用户输入的部分字符提供完整的建议。 - **IP路由**:在网络路由中,Trie可以用于最长前缀匹配问题,快速找到最佳的路由路径。 - **词典实现**:Trie可以用于构建高效的词典系统,支持快速的单词插入、查找和删除操作。 由于Trie的高效性,它在处理大量字符串数据时表现尤为出色。然而,Trie并不是所有场景下的最优选择。对于动态集合数据的查找,散列表或红黑可能更为合适。Trie的优势在于其前缀匹配能力,因此更适合于需要频繁进行前缀匹配查询的场景[^3]。 ### 相关问题 1. Trie哈希表相比有哪些优缺点? 2. 如何优化Trie以减少内存占用? 3. Trie在拼写检查中的具体实现方式是什么? 4. Trie如何支持通配符匹配? 5. Trie能否支持中文字符的处理?如果可以,如何实现?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值