Trie
no node in the same tree stores the key associated with that node Its position in the defines, the key with which it is associated
.
A trie for Keys ' A ', ' to ', ' tea ', ' Ted ', ' Ten ', ' I ', ' in ', and ' Inn ' An example of a radix tree
Radix Tree
Integer Trie
The Trie tree can store bit strings (stirngs of bits) because integers can be represented in binary notation, so trie trees can store integers. As shown in Figure 5.2, the string 0011,011,11 represents a different bit string, but it represents the same integer 3, which is where the problem lies! The workaround is to use the small end integer (the right weight is high), so that 3 is (11) 2,2 is (01) 2.
Python implements Figure 5.3:
#!/usr/bin/python#-*-coding:utf-8-*-classNode:def __init__(self): Self.left= Self.right =None Self.value=NonedefTrieinsert (t, Key,value =None):ifT isNone:t=Node () p=T whileKey! =0:ifKey & 1==0:ifP.left isNone:p.left=Node () p=P.leftElse: ifP.right isNone:p.right=Node () p=p.right Key=key>>1P.value=valuereturnTdefLookup (t,key): whileKey! = 0 and(t is notNone):ifKey & 1 = =0:t=T.leftElse: T=t.right Key= Key>>1ifT is notNone:returnT.valueElse: returnNonedefMain (): T=Node () Trieinsert (T,1,'a') Trieinsert (T,4,'b') Trieinsert (T,5,'C') Trieinsert (T,9,'D') PrintLookup (t,9)if __name__=="__main__": Main ()
View Code
Integer Patricia (Practical algorithm)
Figure5.3 is a waste of space, and an improved approach is path compression -compressing nodes that don't have corresponding keywords. Figure 5.4 (for the time being, add it later)
Alphabetic Trie
Trie trees can also store strings.
#include <stdio.h>#include<stdlib.h>typedefstructnode{structnode* children[ -]; int*data;} Node; Node*Create_node () {node* t = (node*)malloc(sizeof(Node)); inti; for(i=0;i< -; i++) {T->children[i] =NULL; } t->data =NULL; returnT;} Node* Insert (node* t,Const Char* Key,int*value) { intC; Node*p; if(!t) {T=Create_node (); } for(p = t; *key; ++key, p = p->Children[c]) {C= *key-'a'; if(!p->Children[c]) {P->CHILDREN[C] =Create_node (); }} P->data =value; returnt;}int* Lookup (node* t,Const Char*key) { while(*key && t && t->children[*key-'a']) {T= t->children[*key++-'a']; } return(*key | |!t)? Null:t->data;} intMainintargcChar Const*argv[]) {Node*t =Create_node (); Char* ch[3]= {"We","Hello","were"}; intv[3] ={1,2,3}; inti; for(i=0;i<3; i++) {Insert (T, ch[i],v+i); } printf ("%d\n", *lookup (T, ch[1]) ); return 0;}
View Code
Alphabetic Partricia
Cardinality trees (Radix tree)