2—3树
红黑树
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure3
{
class RBT1<E> where E : IComparable<E>
{
private const bool Red = true;
private const bool Black = false;
private class Node
{
public E e;
public Node left;
public Node right;
public bool color;
public Node(E e)
{
this.e = e;
left = null;
right = null;
color = Red;
}
}
private Node root;
private int N;
public RBT1()
{
root = null;
N = 0;
}
public int Count { get { return N; } }
public bool IsEmpty { get { return N == 0; } }
private bool IsRed(Node node)
{
if (node == null)
return Black;
return node.color;
}
//左旋转
private Node LeftRotate(Node node)
{
Node x = node.right;
node.right = x.left;
x.left = node;
x.color = node.color;
node.color = Red;
return x;
}
如果两个子路都是红色,则进行颜色的翻转
//颜色翻转
private void FlipColors(Node node)
{
node.color = Red;
node.left.color = Black;
node.right.color = Black;
}
递归添加元素
//递归方法
public void Add(E e)
{
root = Add(root, e);
root.color = Black;
}
//以node为根的树中添加元素,添加元素后返回根结点
private Node Add(Node node, E e)
{
if (node == null)
{
N++;
return new Node(e);//默认为红节点
}
if (e.CompareTo(node.e) < 0)
node.left = Add(node.left, e);
else if (e.CompareTo(node.e) > 0)
node.right = Add(node.right, e);
//如果出现右子节点是红色,左子节点是黑色 进行左旋转
if(IsRed(node.right)&& !IsRed(node.left))
{
node = LeftRotate(node);
}
//如果出现连续的左子节点都为红色 进行右旋转
if(IsRed(node.left)&&IsRed(node.left.left))
{
node=RightRoatate(node);
}
//如果出现左右节点都是红色,进行颜色翻转
if(IsRed(node.left)&&IsRed(node.right))
{
FlipColors(node);
}
return node;
}
红黑树在集合里的体现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure3
{
class RBT1Set<E>:ISet<E> where E:IComparable<E>
{
private RBT1<E> rbt;
public RBT1Set()
{
rbt = new RBT1<E>();
}
public int Count { get { return rbt.Count; } }
public bool IsEmpty { get { return rbt.IsEmpty; } }
public void Add(E e)
{
rbt.Add(e);
}
public bool Contains(E e)
{
return rbt.Contains(e);
}
public void Remove(E e)
{
Console.WriteLine("待实现");
}
public int MaxHeight()
{
return rbt.MaxHeight();
}
}
}