如题,C# 实现简单的二叉堆的 Push() 和 Pop(), 如有不足欢迎指正。
另外,在C#中使用 Heap 的相似功能可以考虑使用:Priority Queues,SortedDictionary,SortedList 。
using System;
using System.Collections.Generic; namespace LeetCode.BaseClass
{
public enum HeapType
{
MinHeap,
MaxHeap
} public class BinaryHeap<T> where T : IComparable<T>
{
List<T> items; public HeapType HType { get; private set; } public T Root
{
get { return items[]; }
} public BinaryHeap(HeapType type)
{
items = new List<T>();
this.HType = type;
} public void Push(T item)
{
items.Add(item); int i = items.Count - ; bool flag = HType == HeapType.MinHeap; while (i > )
{
if ((items[i].CompareTo(items[(i - ) / ]) > ) ^ flag)
{
T temp = items[i];
items[i] = items[(i - ) / ];
items[(i - ) / ] = temp;
i = (i - ) / ;
}
else
break;
}
} private void DeleteRoot()
{
int i = items.Count - ; items[] = items[i];
items.RemoveAt(i); i = ; bool flag = HType == HeapType.MinHeap; while (true)
{
int leftInd = * i + ;
int rightInd = * i + ;
int largest = i; if (leftInd < items.Count)
{
if ((items[leftInd].CompareTo(items[largest]) > ) ^ flag)
largest = leftInd;
} if (rightInd < items.Count)
{
if ((items[rightInd].CompareTo(items[largest]) > ) ^ flag)
largest = rightInd;
} if (largest != i)
{
T temp = items[largest];
items[largest] = items[i];
items[i] = temp;
i = largest;
}
else
break;
}
} public T PopRoot()
{
T result = items[]; DeleteRoot(); return result;
}
} }