簡體   English   中英

.NET 4.0 中有內置的二叉搜索樹嗎?

[英]Is there a built-in Binary Search Tree in .NET 4.0?

.NET 4.0 中是否有內置的二叉搜索樹,還是我需要從頭開始構建這種抽象數據類型?

編輯

這具體是關於二叉搜索樹,而不是一般的抽象數據類型“樹”。

我認為System.Collections.Generic中的SortedSet<T>類是您正在尋找的。

從此CodeProject 文章

它是使用自平衡紅黑樹實現的,該樹為插入、刪除和查找提供了O(log n)的性能復雜度。 它用於保持元素排序,獲取特定范圍內元素的子集,或獲取集合的最小最大元素。

源代碼https://github.com/dotnet/corefx/blob/master/src/System.Collections/src/System/Collections/Generic/SortedSet.cs

在我提出這個問題五年后,我意識到 .NET 4.0 中確實有一個內置的二叉搜索樹。 它可能是稍后添加的,並且可以按預期工作。 它在每次插入后進行自我平衡(遍歷),這會降低添加大量項目時的性能。

SortedDictionary<TKey, TValue>類有以下備注:

SortedDictionary 泛型類是具有 O(log n) 檢索的二叉搜索樹,其中 n 是字典中的元素數。 在這方面,它類似於 SortedList 泛型類。 這兩個類具有相似的對象模型,並且都具有 O(log n) 檢索。

不,.NET 不包含二叉搜索樹 它確實包含一個紅黑樹,它是一種特殊的二叉搜索樹,其中每個節點都被塗成紅色或黑色,並且使用這些顏色有一些規則可以保持樹的平衡並允許樹保證O(logn)搜索次。 標准的二叉搜索樹不能保證這些搜索時間。

該類稱為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

可以在http://code.google.com/p/self-balancing-avl-tree/上找到一個C#平衡的AVL二叉樹。它還實現了對數連接和拆分操作

C5 集合庫(參見http://www.itu.dk/research/c5/ )包括具有平衡紅黑二叉樹的TreeDictionary<>類。 注意:我還沒有使用過這個庫,因為我所做的工作只需要標准的 .NET 集合。

答案是不。

雖然有可用的實現。 看看以下鏈接:

C#中的二叉樹

感謝 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();
        }
    }
}

我不確定您對“樹”的確切含義,但您可以在 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 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM