这是我的代码:
class BinaryTree<T> { private node<T> Head; public class node<T> { public T Data; public node<T> right; public node<T> left; public node<T> parent; ... } ... private void insert(ref T data,node<T> parent,ref node<T> currentChild) { ... { if (currentChild.Data >= data) insert(ref data,currentChild,ref currentChild.right); else insert(ref data,ref currentChild.left); } } }
在上面if(currentChild.Data> = data)我得到错误:
Operator ‘>=’ cannot be applied to operands of type ‘T’ and ‘T’
解决方法
这个问题的经典解决方案是(1)使T
IComparable<T>
,或(2)使用
IComparer<T>
或仿函数到您的班级.
(1)
class BinaryTree<T> where T : Comparable<T> ...
(2)
class BinaryTree<T> { private node<T> Head; private readonly IComparer<T> comparer; public BinaryTree(IComparer<T> comparer) { this.comparer = comparer; } //... }