红黑树
基于二叉查找树的优化,优化了什么,当二叉查找树遇到有序数组时,性能损失大,会退化成一条链表,且树高度最高,所以引入红黑树进行优化,通过对树的不断左旋,右旋,颜色翻转,来使树得到平衡
RedTree.cs
class RedTree<T> where T:IComparable<T>
{
private const bool Red=true;
private const bool Black=false;
private class Node
{
public T Val { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public bool Color { get; set; }
public Node(T val)
{
this.Val=val;
this.Left=null;
this.Right=null;
Color=Red;
}
}
private Node root; //我们的根节点
private int N; //存储元素的个数
public RedTree() //当我们实例一个对象时候初始化
{
root=null;
N=0;
}
public int Count { get{return N;} }
public bool IsEmpty {get{return N==0;}} //N为0代表没有节点
//判断颜色
private bool IsRed(Node root)
{
if(root==null) return Black;
return root.Color;
}
//子操作,左旋转
private Node LeftRotate(Node root)
{
Node x=root.Right;
root.Right=x.Left;
x.Left=root;
x.Color=root.Color;
root.Color=Red;
return x;
}
//右旋转
private Node RightRotate(Node root)
{
Node x=root.Left;
root.Left=x.Right;
x.Right=root;
x.Color=root.Color;
root.Color=Red;
return x;
}
//反转颜色
private void FlipColors(Node root)
{
root.Color=Red;
root.Left.Color=Black;
root.Right.Color=Black;
}
//递归方式添加新元素
public void Add(T val)
{
root=Add(root,val);
root.Color=Black;
}
private Node Add(Node Root,T val)
{
if(Root==null)
{
N++;
return new Node(val); //默认为红色
}
if(val.CompareTo(Root.Val)<0)
{
Root.Left=Add(Root.Left,val); //递归到最后会返回一个Node节点,用left去接住
}
if(val.CompareTo(Root.Val)>0)
{
Root.Right=Add(Root.Right,val); //同理
}
//如果根的右节点为红色,左节点为黑色,进行左旋转
if(IsRed(Root.Right)&&!IsRed(Root.Left))
Root=LeftRotate(Root);
//如果根的左节点为红色,左节点的左节点也为红色,进行右旋转
if(IsRed(Root.Left)&&IsRed(Root.Left.Left))
Root=RightRotate(Root);
//如果左右颜色均为红色,进行颜色翻转
if(IsRed(Root.Left)&&IsRed(Root.Right))
FlipColors(Root);
return Root;
}
//查找元素
public bool Contains(T val)
{
return Contains(root,val);
}
private bool Contains(Node Root,T val)
{
if(Root==null)
{
return false;
}
if(val.CompareTo(Root.Val)==0)
{
return true;
}
else if(val.CompareTo(Root.Val)<0)
{
return Contains(Root.Left,val);
}
else
{
return Contains(Root.Right,val);
}
}
//树的高度取值
public int MaxHeight()
{
return MaxHeight(root);
}
private int MaxHeight(Node Root)
{
if(Root==null) return 0;
int l=MaxHeight(Root.Left);
int r=MaxHeight(Root.Right);
return Math.Max(l,r)+1;
}
}
Program.cs
class Test
{
static void Main(string[] arg)
{
RedTree<int> tree=new RedTree<int>();
int[] a={1,2,3,4,5,6,7,8,9};
for(int i=0;i<a.Length;i++)
{
tree.Add(a[i]);
}
int h=tree.MaxHeight();
System.Console.WriteLine(h);
}
}

浙公网安备 33010602011771号