After reading the masterpiece of Jeffery Zhao, I had the impulse to write a Prefix Tree, so it took a little time to implement it.
[Edit] found many vulnerabilities in this implementation and hidden them ...... Really want to see, click here to expand
Code:
Using System . Collections . Generic; Namespace Datastructure . Trees { Public sealed class Trie < Tkeyfragment, tvalue > { Private Trienode < Tkeyfragment, tvalue > Root; Public Trie () {Root = New Trienode < Tkeyfragment, tvalue > ();} Public Trie ( Trienode < Tkeyfragment, tvalue > Root ){ This . Root = Root ;} Public bool Store ( Ienumerable < Tkeyfragment > Key, tvalue value ){ Return Root . Expand (Key . Getenumerator (), value );} Public Ienumerable < Tvalue > Lookfor ( Ienumerable < Tkeyfragment > Key ){ Return Root . Lookfor (Key . Getenumerator ());}} Public class Trienode < Tkeyfragment, tvalue > { Protected Dictionary < Tkeyfragment, Trienode < Tkeyfragment, tvalue > Table = New Dictionary < Tkeyfragment, Trienode < Tkeyfragment, tvalue > (); Protected List < Tvalue > Valuecollection = New List < Tvalue > (); Protected internal virtual bool Expand ( Ienumerator < Tkeyfragment > Keyenumerator, tvalue value ){ If (Keyenumerator . Movenext ()){ VaR Nextfragment = Keyenumerator . Current; If ( ! Table . Containskey (nextfragment) {table . Add (nextfragment, New Trienode < Tkeyfragment, tvalue > ());} Return Table [nextfragment] . Expand (keyenumerator, value );} Else { If ( ! This . Valuecollection . Contains (value )){ This . Valuecollection . Add (value );} Return true ;}} Protected internal virtual Ienumerable < Tvalue > Lookfor ( Ienumerator < Tkeyfragment > Keyenumerator ){ If (Keyenumerator . Movenext ()){ VaR Nextfragment = Keyenumerator . Current; If ( ! Table . Containskey (nextfragment )){ Return new List < Tvalue > ();} Return Table [nextfragment] . Lookfor (keyenumerator );} Else { Return Valuecollection ;}}}}
The key type must be ienumerable <tkeyfragment>. The usage is simple:
Class Program { Static void Main ( String [] ARGs ){ VaR Mytrie = New Trie < Char , String > (); Mytrie . Store ( "I love you" , "Guys" ); Mytrie . Store ( "I love you" , "Cnblogs" ); Mytrie . Store ( "I hate you" , "Bad guy" ); Mytrie . Store ( "I hate you" , "WTF" ); Mytrie . Lookfor ( "I love you" ) . Tolist () . Foreach (Str => Console . Writeline (STR); mytrie . Lookfor ( "I hate you" ) . Tolist () . Foreach (Str => Console . Writeline (STR ));}}
I haven't thought about how to merge the intermediate nodes with no corresponding value. Let's go back and think about it.