❖ Tries |
A trie …
Note: Trie comes from retrieval ; but pronounced as "try" not "tree"
❖ ... Tries |
Each node in a trie …
Depth d of trie = length of longest key value
❖ ... Tries |
Possible trie representation:
#define ALPHABET_SIZE 26 typedef struct Node *Trie; typedef struct Node { char onechar; // current char in key Trie child[ALPHABET_SIZE]; bool finish; // last char in key? Item data; // no Item if !finish } Node; typedef char *Key; // just lower-case letters
❖ ... Tries |
Above representation is space inefficient
Could reduce branching factor by reducing "alphabet"
❖ Searching in Tries |
Search requires traversing a path, char-by-char from Key:
find(trie,key): | Input trie, key | Output pointer to element in trie if key found | NULL otherwise | | node=trie | for each char c in key do | | if node.child[c] exists then | | node=node.child[c] // move down one level | | else | | return NULL | | end if | end for | if node.finish then // "finishing" node reached? | return node | else | return NULL | end if
❖ Insertion into Tries |
Insertion into a Trie ...
Trie insert(trie,item,key):
| Input trie, item with key of length m
| Output trie with item inserted
|
| if trie is empty then
| | t=new trie node
| end if
| if m=0 then // end of key
| | t.finish=true, t.data=item
| else
| | first=key[0], rest=key[1..m-1]
| | t.child[first]=insert(t.child[first],item,rest)
| end if
| return t
❖ Cost Analysis |
Analysis of standard trie:
❖ Example Trie |
Example text and corresponding trie of searchable words:
Note: trie has no prefixes ⇒ all finishing nodes are leaves
❖ Compressed Tries |
Compressed tries …
❖ ... Compressed Tries |
Compact representation of compressed trie to encode array S of strings:
Produced: 11 Jul 2020