我有一个通用二叉树,它将在左边添加小于或等于到的对象,并在右边添加大于的对象。我的问题是比较泛型,我知道数据值将是对象包装的原语或字符串,因此它们是可比较的。但是,我不知道如何在代码中实现这一点。
该代码正在进行中,我知道add方法尚未正确添加,但是我正在努力。谢谢
这是TreeNode:
public class TreeNode<T>
{
//Instance Variables
TreeNode leftChild;
TreeNode rightChild;
int childCount;
int depth;
T data;
public TreeNode(T data, int parentDepth)
{
leftChild = null;
rightChild = null;
childCount = 0;
depth = parentDepth + 1;
this.data = data;
}
public TreeNode(int parentDepth)
{
leftChild = null;
rightChild = null;
childCount = 0;
depth = parentDepth + 1;
data = null;
}
public void add(T data)
{
if (this.data.compareTo(data) <= 0)
{
addLeft(data);
} else if (this.data.compareTo(data) > 0)
{
addRight(data);
} else
{
System.out.println("ERROR IN TREENODE.ADD");
}
}
public void addLeft(T data)
{
leftChild = new TreeNode(data, depth);
}
public void addLeft()
{
leftChild = new TreeNode(depth);
}
public void addRight(T data)
{
rightChild = new TreeNode(data, depth);
}
public void addRight() {
rightChild = new TreeNode(depth);
}
}
最佳答案
我知道数据值将是对象包装的原始数据或字符串,因此它们具有可比性。
然后,您可以告诉编译器:
public class TreeNode<T extends Comparable<T>>
如果这样做,您将可以访问在
compareTo
中定义的Comparable
方法。