在AVL树中使用icomparable

时间:2011-12-06 20:02:21

标签: c# data-structures binary-search-tree avl-tree

 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 ..任何人都告诉它缺少什么呢??????????????

1 个答案:

答案 0 :(得分:0)

您的element属性属于object类型,因此它不会实现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);
    }
}