问题描述
我已经创建了一个AVL树实现(感谢https://www.geeksforgeeks.org/),并对其进行了一些修改以满足我的需要。基本上,我希望能够通过一个键找到一个节点(就像在我有键-值对的字典中一样)。
我尝试优化以下代码,该代码在树中搜索一个单词,如果不存在,则会添加它:
// If the word doesn't exist,we do 2 searches and therefore we get O(2*lg(n)) = O(lg(n^2))
private void AddWordAppearance(string word)
{
Word wordobject = wordsDictionary[word]; // Search the word in the tree - O(lg(n))
// If the word doesn't exist,create the Word instance and add it to the dictionary.
if (wordobject == null)
{
wordobject = new Word(word); // O(1)
wordsDictionary.Add(word,wordobject); // O(lg(n))
}
// Some code that sets things in the wordobject.
}
我从约100MB的文本文件中获取单词,并且我的算法在约50秒内构建了树。
// The key and Value are the generic type parameters of the AVL tree.
public Value FindOrAdd(Key key,Value toAdd)
{
if (Root == null)
{
Add(key,toAdd);
return toAdd;
}
DictionaryEntryNode<Key,Value> entry = Root,prevIoUs = null;
while(entry != null)
{
prevIoUs = entry;
if (entry < key)
{
entry = entry.right;
}
else if (entry > key)
{
entry = entry.left;
}
else
{
return entry.value;
}
}
Insert(prevIoUs,key,toAdd);
return toAdd;
}
我认为它的运行速度会更快,因为现在我的算法需要执行一次搜索,而不是两次(搜索并插入)。
但是我得到的结果几乎相同。
有什么我想念的吗?
- 我使用Stopwatch类计算构建树的时间。
===编辑===
public void Add(Key key,Value value) => this.Root = Insert(Root,value);
private static DictionaryEntryNode<Key,Value> Insert(DictionaryEntryNode<Key,Value> node,Key key,Value value)
{
if (node == null)
return new DictionaryEntryNode<Key,Value>(key,value);
// If the given key is smaller than the node's key,we try to insert in the left sub-tree.
if (node > key)
node.left = Insert(node.left,value);
// If the given key is greater than the node's key,we try to insert in the right sub-tree.
else if (node < key)
node.right = Insert(node.right,value);
// If the key already exists,we simply return the node (duplicates aren't allowed).
else
return node;
// And Eventually re-balance the node.
return Rebalance(node,key);
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)