1 / 15

Trie 树 —— 一种实用的树形结构

Trie 树 —— 一种实用的树形结构. 主讲: 杜川 软件学院 04 级. 内容提要 :. 什么是 Trie 树? Trie 树的性质和特点 Trie 树的实现 Trie 树是做什么的?. 什么是 Trie 树?. Trie 树的定义: Trie 树是一棵度 m ≥ 2 的树,它的每一层分支不是靠整个关键码的值来确定,而是由关键码的一个分量来确定。 树的 “ 度 ” ? 关键码? ID ,标识符,字符串. 什么是 Trie 树?. Root. A. 字符串“ A”. C. T. 字符串“ AC”. 字符串“ AT”. M. N. N.

Télécharger la présentation

Trie 树 —— 一种实用的树形结构

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Trie树——一种实用的树形结构 主讲: 杜川 软件学院04级

  2. 内容提要: • 什么是Trie树? • Trie树的性质和特点 • Trie树的实现 • Trie树是做什么的?

  3. 什么是Trie树? • Trie树的定义:Trie树是一棵度 m ≥ 2 的树,它的每一层分支不是靠整个关键码的值来确定,而是由关键码的一个分量来确定。 • 树的“度”? • 关键码? ID,标识符,字符串

  4. 什么是Trie树? Root A 字符串“A” C T 字符串“AC” 字符串“AT” M N N

  5. Trie树的性质和特点 • 性质: • 根节点不包含字符,除根节点外每一个节点都只包含一个字符。 • 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。 • 每个节点的所有子节点包含的字符都不相同。 (要求)

  6. Trie树的性质和特点 • 特点: • 空间: • 前缀相同的字串共享相同的祖先节点。 • 节省空间?变化趋势? • 时间 • 查询速度快。 • O(length) • 与O(N)和O(lgN)不是同一级别的概念

  7. Trie树的实现 • 结构体 struct trieNode { trieNode * next[26]; bool isword; }Root;

  8. Trie树的实现 • 插入同时也是建树的过程 void insert(char * tar) { trieNode * p = & Root; int id; while(*tar) { id = *tar –‘a’; if(p->next[id] == NULL) { p->next[id] = new trieNode(); } p = p->next[id]; tar ++; } p->isword = true; }

  9. Trie树的实现 • 查询 bool search(char * tar) { trieNode * p = & Root; int id; while(*tar) { id = *tar –‘a’; if(p->next[id] == NULL) { return false; } p = p->next[id]; tar ++; } if ( p->isword == true ) return true; else return false; }

  10. Trie树是做什么的? 例1:现有一海量词典, • 其中的词由小写英文字符串组成; • 单词个数达到2,000,000个; • 每个单词长度不超过10。 问题:任意给出一个单词(当然该单词符合以上条件),问该单词是否在该词典中。

  11. Trie树是做什么的? • 解法一:硬搜 1000^2 • 解法二:用STL的set • 解法三:输入后排序,再用二分查找 • 解法四:Trie树 • 三种方法的 时空复杂度 O?

  12. Trie树是做什么的? • 例2:PKU 2503 Babelfish • Sample Input • dog ogday • cat atcay • pig igpay • froot ootfray • loops oopslay • atcay • ittenkay • oopslay • Sample Output • cat • eh • loops

  13. Trie树是做什么的? • 例3: • PKU • 1204 • Word Puzzles • 1000 * 1000 • 8个方向 • 1000个待查单词 • MARGARITA • 0 15 G

  14. Trie树是做什么的? • 例4:PKU 2513 Colored Sticks • Sample Input • blue red • red violet • cyan blue • blue magenta • magenta cyan • Sample Output • Possible • Total Of Sticks • Up To 250000 • 欧拉回路 • 节点存储使用

  15. 谢谢!!

More Related