我试图将AVL树转换为通用,但我面临几个类型错误。
操作符不能用于'T'和'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;
编辑:在我发布这篇文章之前,我设法剪掉了一个代码片段。
首先,Node类中的泛型类型需要实现iccomparable接口才能做到这一点。
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;
}
}
其次,iccomparable不会重载'<'和'>'操作符。你需要这样做
else if (n.data.CompareTo(current.data) < 0) {
current.left = RecursiveInsert(current.left, n);
current = balance_tree(current);
}
您可以从Comparer<T>.Default
获得通用比较器。
public class Node
{
public static readonly IComparer<T> comparer = Comparer<T>.Default;
}
然后你可以用它来比较泛型类型。
int c = Node.comparer.Compare(n.data, current.data);
if (c < 0) {
current.left = RecursiveInsert(current.left, n);
current = balance_tree(current);
}
else if (c > 0) {
current.right = RecursiveInsert(current.right, n);
current = balance_tree(current);
}