Here is my code:
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, currentChild, ref currentChild.left);
}
}
}
Above at point if (currentChild.Data >= data)
I am getting error :
Operator '>=' cannot be applied to operands of type 'T' and 'T'
What do I do to resolve the error?
You need to specify that T implements IComparable so that you can compare:
class BinaryTree<T> where T : IComparable<T>
{
...
public class node<T> where T : IComparable<T> ...
...
if (currentChild.Data.CompareTo(data) >= 0) ...
...
}
The classic solutions to this problem are (1) to make T
IComparable<T>
, or (2) to use an IComparer<T>
or a functor to your class.
(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;
}
//...
}
I don't know about C#, but in Java you would need to have an instance of a generic Comparator class, parametrized with the types you want to compare. This generic class provided a compareTo() function which would be implemented in a way that allows for comparison of the two types.
T should be a type that implements IComparable and then use its compareto to method instead of >=. Operator overloading is another option if you still want to support >=.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With