Click here to Skip to main content
15,906,569 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I have B where I am trying to implement it using generics so that any key,value pair data type can be used when instantiated. However, I get stuck on the compare below.
I just simply want to compare values return -1,0 or 1 and do normal binary search tree operations


C#
public class RedBlackBST<TKey, TValue> 
     {
          private Node root;
          public int redCount = 0;
          public int totalNodes = 0;
          private static Boolean RED = true;
          private static Boolean BLACK = false;

          private class Node
          {
.
.
.
.
.
.

private Node put(Node h, TKey key, TValue val)
          {
               if (h == null) // Do standard insert, with red link to parent.
               {
                    return new Node(key, val, 1, RED);
               }
               int cmp = key.compareTo(h.key); //This is where I get stuck
               if (cmp < 0)
               {
                    h.left = put(h.left, key, val);
               }
               else if (cmp > 0)
               {
                    h.right = put(h.right, key, val);
               }
               else
               {
                    h.val = val;
               }
               if (isRed(h.right) && !isRed(h.left))
               {
                    h = rotateLeft(h);

               }
               if (isRed(h.left) && isRed(h.left.left))
               {
                    h = rotateRight(h);

               }
               if (isRed(h.left) && isRed(h.right))
               {
                    flipColors(h);

               }
               h.N = size(h.left) + size(h.right) + 1;
               return h;
          }
Posted
Comments
Sergey Alexandrovich Kryukov 30-Mar-12 2:00am    
OK, and what is the problem?
--SA

You must tell that the TKey is IComparable.

C#
public class RedBlackBST<TKey, TValue> where TKey: IComparable
{
   ...
} 
 
Share this answer
 
It isn't very clear what the exact error is, but looking at where you get stuck it looks like the key ojects aren't comparable. Check msdn for more info:
http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx[^]

Good luck!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900