Search code examples
c#binary-search-treeavl-tree

C# Gives CS0019 Error: Operator cannot be applied to operands of type 'T' and 'T'


Im trying to convert AVL tree to Generic but I faced couple of type errors.

Operator cannot be applied to operands of type 'T' and 'T'

 private Node RecursiveInsert(Node current, Node n)
{
    if (current == null)
    {
        current = n;
        return current;
    }
    else if (n.data < current.data) // Gives Error        {
        current.left = RecursiveInsert(current.left, n);
        current = balance_tree(current);
    }
    else if (n.data > current.data) // Gives Error        {
        current.right = RecursiveInsert(current.right, n);
        current = balance_tree(current);
    }
    return current;
}

///

 public class Node
{
    public T data { get; set; }
    public Node left { get; set; }
    public Node right { get; set; }
    public Node(T data)
    {
        this.data = data;
    }
}
public Node root;

Solution

  • Edit: somehow I managed to cut out a code snippet before I posted this.

    First of all, the generic type in the Node class needs to implement the ICompareable interface to do this.

     public class Node<T> where T : ICompareable
     {
         public T data { get; set; }
         public Node<T> left { get; set; }
         public Node<T> right { get; set; }
         public Node<T>(T data)
         {
             this.data = data;
         }
     }
    

    Second of all, ICompareable doesn't overload the '<' and '>' operators. You need to do something like this instead

    else if (n.data.CompareTo(current.data) < 0) {
        current.left = RecursiveInsert(current.left, n);
        current = balance_tree(current);
    }