我正在开发一个Trie
数据结构,其中每个节点代表一个单词。因此,st
,stack
,stackoverflow
和overflow
字词将被安排为
root
--st
---stack
-----stackoverflow
--overflow
My Trie在内部使用HashTable
,因此所有节点查找都需要一段时间。以下是我将算法插入到trie中的算法。
key
中的每个字符并检查该字的存在。这样做直到我们得到一个节点,其中新值可以作为子节点添加。如果未找到任何节点,则会将其添加到根节点下。我不确定这是实现trie的正确方法。欢迎任何建议或改进。
使用的语言:C ++
答案 0 :(得分:6)
trie应该看起来像这样
ROOT
overflow/ \st
O O
\ack
O
\overflow
O
通常,您不需要将哈希表用作trie的一部分; trie本身已经是一种有效的索引数据结构。当然你可以做到。
但是无论如何,你的步骤(2)实际上应该在搜索期间下降trie而不仅仅是查询哈希函数。通过这种方式,您可以轻松找到插入点,而不需要在以后单独搜索它。
我相信第(3)步是错误的,你不需要重新安排一个特里,事实上你不应该这样做,因为它只是额外的字符串碎片你存放在特里;见上图。
答案 1 :(得分:1)
以下是插入算法的java代码。
public void insert(String s){
Node current = root;
if(s.length()==0) //For an empty character
current.marker=true;
for(int i=0;i<s.length();i++){
Node child = current.subNode(s.charAt(i));
if(child!=null){
current = child;
}
else{
current.child.add(new Node(s.charAt(i)));
current = current.subNode(s.charAt(i));
}
// Set marker to indicate end of the word
if(i==s.length()-1)
current.marker = true;
}
}
有关更详细的教程,请参阅here。
答案 2 :(得分:0)
你有没有机会看到这个...... http://linux.thai.net/~thep/datrie/datrie.html#Insert