在.NET 4.0中是否有内置的二叉搜索树,还是需要从头开始构建这个抽象数据类型?
编辑
这是关于二叉搜索树特别地,而不是一般意义上的“树”这种抽象数据类型。
在.NET 4.0中是否有内置的二叉搜索树,还是需要从头开始构建这个抽象数据类型?
这是关于二叉搜索树特别地,而不是一般意义上的“树”这种抽象数据类型。
System.Collections.Generic
中的 SortedSet<T>
类是你要寻找的内容。SortedSet.First()
应该返回 BST 的根节点吗?如果不是,它是返回第一个添加的项吗?还是最后添加的项? - joym8五年后,我才意识到在 .NET 4.0 中确实有内置的二叉搜索树。它可能是在之后添加的,并且按预期工作。每次插入后它会自我平衡(遍历),这会降低在添加大量项时的性能。
SortedDictionary<TKey, TValue>
类有以下备注:
SortedDictionary 泛型类是具有 O(log n) 检索的二叉搜索树,其中 n 是字典中元素的数量。在这方面,它类似于 SortedList 泛型类。这两个类具有相似的对象模型,且都具有 O(log n) 检索。
SortedSet<T>
}},并在.NET 4.0中引入。您可以查看它的源代码此处。以下是其用法示例:// Created sorted set of strings.
var set = new SortedSet<string>();
// Add three elements.
set.Add("net");
set.Add("net"); // Duplicate elements are ignored.
set.Add("dot");
set.Add("rehan");
// Remove an element.
set.Remove("rehan");
// Print elements in set.
foreach (var value in set)
{
Console.WriteLine(value);
}
// Output is in alphabetical order:
// dot
// net
C5集合库(请参见http://www.itu.dk/research/c5/)包括带有平衡红黑二叉树的TreeDictionary<>
类。注意:我还没有使用这个库,因为我的工作只需要标准的.NET集合。
感谢herzmeister der welten,我现在知道了!我尝试了一下,结果真的有效!
namespace Tree
{
public partial class Form1 : Form
{
private SortedSet<int> binTree = new SortedSet<int>();
public Form1()
{
InitializeComponent();
}
private void Insert(int no)
{
binTree.Add(no);
}
private void Print()
{
foreach (int i in binTree)
{
Console.WriteLine("\t{0}", i);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
Insert(Int32.Parse(tbxValue.Text));
tbxValue.Text = "";
}
private void btnPrint_Click(object sender, EventArgs e)
{
Print();
}
}
}
我不确定你所说的“tree”具体指什么,但是你可以在List类上执行二分搜索。
public int BinarySearch( T item );
public int BinarySearch( T item, IComparer<T> comparer );
public int BinarySearch( int index, int count, T item, IComparer<T> comparer );