基于 C# 的红黑树扩展数据结构实现技术文档
简介
红黑树(Red-Black Tree)是一种自平衡二叉搜索树,通过重新着色和旋转操作,在插入和删除节点时保持平衡,从而保证查找、插入和删除操作的时间复杂度为 O ( log n ) O(\log n) O(logn)。本技术文档详细介绍了如何在C#中实现红黑树,并扩展其功能以支持更多操作。
红黑树的特性
- 每个节点要么是红色,要么是黑色。
- 根节点是黑色。
- 每个叶子节点(NIL节点)是黑色。
- 如果一个节点是红色,则它的两个子节点都是黑色。
- 从一个节点到该节点的所有后代叶子节点的简单路径上,均包含相同数目的黑色节点。
代码实现
节点类定义
public enum Color {
Red, Black }
public class RedBlackTreeNode<TKey, TValue>
{
public TKey Key {
get; set; }
public TValue Value {
get; set; }
public Color NodeColor {
get; set; }
public RedBlackTreeNode<TKey, TValue> Left {
get; set; }
public RedBlackTreeNode<TKey, TValue> Right {
get; set; }
public RedBlackTreeNode<TKey, TValue> Parent {
get; set; }
public RedBlackTreeNode(TKey key, TValue value)
{
Key = key;
Value = value;
NodeColor = Color.Red;
Left = null;
Right = null;
Parent = null;
}
}
红黑树类定义
public class RedBlackTree<TKey, TValue> where TKey : IComparable<TKey>
{
private RedBlackTreeNode<TKey, TValue> root;
public void Insert(TKey key, TValue value)
{
RedBlackTreeNode<TKey, TValue> newNode = new RedBlackTreeNode<TKey, TValue>(key, value);
if (root == null)
{
root = newNode;
root.NodeColor = Color.Black;
}
else
{
Insert(root, newNode);
FixInsert(newNode);
}
}
private void Insert(RedBlackTreeNode<TKey, TValue> current, RedBlackTreeNode<TKey, TValue> newNode)
{
int compare = newNode.Key.CompareTo(current.Key);
if (compare < 0)
{
if (current.Left == null)
{
current.Left = newNode;
newNode.Parent = current;
}
else
{
Insert(current.Left, newNode);
}
}
else
{
if (current.Right == null)
{
current.Right = newNode;
newNode.Parent = current;
}
else
{
Insert(current.Right, newNode);
}
}
}
private void FixInsert(RedBlackTreeNode<TKey, TValue> node)
{
while (node != root && node.Parent.NodeColor == Color.Red)
{
if (node.Parent == node.Parent.Parent.Left)
{
RedBlackTreeNode<TKey, TValue> uncle = node.Parent.Parent.Right;
if (uncle != null && uncle.NodeColor == Color.Red)
{
node.Parent.NodeColor = Color.Black;
uncle.NodeColor = Color.Black;
node.Parent.Parent.NodeColor = Color.Red