I was just doing some research on RedBlack Tree. I knew that SortedSet class in .Net 4.0 uses RedBlack tree. So I took that part out as is using Reflector and created a RedBlack
You have a bug in your Node
class. When you call the constructor that only takes a single value argument you should be setting IsRed
to true
.
I suppose that the fixed Node
class should look something like this:
public sealed class Node
{
public T Item { get; private set; }
public bool IsRed { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public Node(T value)
{
Item = value;
IsRed = true;
}
public Node(T value, bool isRed)
{
Item = value;
IsRed = isRed;
}
}
Another option -- my preference -- would be to omit that constructor altogether and always require IsRed
to be set explicitly when you instantiate a new node:
public sealed class Node
{
public T Item { get; private set; }
public bool IsRed { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public Node(T value, bool isRed)
{
Item = value;
IsRed = isRed;
}
}
And then replace this line in your Add
method...
Node current = new Node(item);
...with this...
Node current = new Node(item, true);