算法&数据结构系列 — Trie树(字典树)


概念

字典树是干嘛用的呢?

for example, Luogu P2580

快速的查找一个字符串有没有出现过,这是trie的本能。

那么,trie是如何工作的呢?请看下图:

trie_example.png

这个图可以表示

a,an,do,dog,zoo,zed六个单词

为什么呢?

如果一个节点是黑色,就表示从根目录一直到这个节点的值连起来是存在的单词。

什么意思?比如,g是黑色,他表示的就是

d+o+g = dog

那为什么点z的儿子o不能表示单词zo呢?

因为他是白色的。。。

very easy,yes?

所以,我们来想一想他的时间&空间复杂度(假设存储的是小写字母)---

时间复杂度:$ O(len Word) $

空间复杂度:$ O(26^{len Word}) $

所以,trie树不但时空复杂度小,还支持精确查找。

代码实现

#define MAX_NUM 26
enum NODE_TYPE{ COMPLETED, UNCOMPLETED };
struct Node {
  enum NODE_TYPE type;
  char ch;
  struct Node* child[MAX_NUM]; //26-tree->a, b ,c, .....z
};
 
struct Node* ROOT; //tree root
 
struct Node* createNewNode(char ch){
  // create a new node
  struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
  new_node->ch = ch;
  new_node->type == UNCOMPLETED;
  int i;
  for(i = 0; i < MAX_NUM; i++)
    new_node->child[i] = NULL;
  return new_node;
}
 
void initialization() {
//intiazation: creat an empty tree, with only a ROOT
ROOT = createNewNode(' ');
}
 
int charToindex(char ch) { //a "char" maps to an index<br>
return ch - 'a';
}
 
int find(const char chars[], int len) {
  struct Node* ptr = ROOT;
  int i = 0;
  while(i < len) {
   if(ptr->child[charToindex(chars[i])] == NULL) {
   break;
  }
  ptr = ptr->child[charToindex(chars[i])];
  i++;
  }
  return (i == len) && (ptr->type == COMPLETED);
}
 
void insert(const char chars[], int len) {
  struct Node* ptr = ROOT;
  int i;
  for(i = 0; i < len; i++) {
   if(ptr->child[charToindex(chars[i])] == NULL) {
    ptr->child[charToindex(chars[i])] = createNewNode(chars[i]);
  }
  ptr = ptr->child[charToindex(chars[i])];
}
  ptr->type = COMPLETED;
}

转载于:https://www.cnblogs.com/mchmch/p/algo-trie.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值