0
 public class Node : IComparable

{
    public object element;
    public Node left;
    public Node right;
    public int height;


    public Node(object data, Node L, Node R)
    {

        element = data;
        left = L;
        right = R;
        height = 0;


    }
    public Node(object data)
    {

        element = data;
        left = null;
        right = null;
        height = 0;


    }

    public int CompareTo(object obj)
    {
        return (this.element.CompareTo((Node)obj.element));


    }


}

在这个 avl 树中,我想为它比较左右节点和其他平衡方法,但在起点它不支持在这行代码中的 compareto

 public int CompareTo(object obj)
    {
        return (this.element.CompareTo((Node)obj.element));


    }

虽然我使用了接口 Icomaparable..任何人都告诉它里面缺少什么??????????????

4

1 回答 1

0

您的element属性是对象类型,因此它不实现IComparable. T相反,您可以创建一个具有类型数据元素必须实现的约束的泛型类IComparable<T>

public class Node<T> : IComparable<Node<T>> where T: IComparable<T>
{
    public T element;
    public Node<T> left;
    public Node<T> right;
    public int height;


    public Node(T data, Node<T> L, Node<T> R)
    {

        element = data;
        left = L;
        right = R;
        height = 0;


    }
    public Node(T data)
    {

        element = data;
        left = null;
        right = null;
        height = 0;


    }

    public int CompareTo(Node<T> other)
    {
        return element.CompareTo(other.element);
    }
}
于 2011-12-06T20:09:43.070 回答