前一篇文章介绍了Trie树,它实现简单但空间效率低。如果要支持26个英文字母,每个节点就要保存26个指针,由于节点数组中保存的空指针占用了太多内存,让我来看看Ternary Tree。
When you have to store a set of strings, what data structure should you use? You could use hash tables, which sprinkle the strings throughout an array. Access is fast, but information about relative order is lost. Another option is the use of binary search trees, which store strings in order, and are fairly fast. Or you could use digital search tries, which are lightning fast, but use lots of space.
In this article, we’ll examine ternary search trees, which combine the time efficiency of digital tries with the space efficiency of binary search trees. The resulting structure is faster than hashing for many typical search problems, and supports a broader range of useful problems and operations. Ternary searches are faster than hashing and more powerful, too.
三叉搜索树Ternary Tree,结合了字典树的时间效率和二叉搜索树的空间效率优点。为了避免多余的指针占用内存,每个Trie节点不再用数组来表示,而是表示成“树中有树”。Trie节点里每个非空指针都会在三叉搜索树里得到属于它自己的节点。
Each node has 3 children: smaller (left), equal (middle), larger (right).
Follow links corresponding to each character in the key.
・If less, take left link; if greater, take right link.
・If equal, take the middle link and move to the next key character.
Search hit. Node where search ends has a non-null value.
Search miss. Reach a null link or node where search ends has null value.
// C program to demonstrate Ternary Search Tree (TST) insert, travese
// and search operations
#include <stdio.h>