问题描述
我需要编写一个方法T bigOnLevel(int lev),该方法查找级别lev上具有最大值的节点。由于我是Java泛型的新手,因此T出现了问题。我的想法是将rightChild / leftChild子树的高度与lev比较,以便知道子树中该层上是否存在节点:
if(!rightChild.isEmpty() && rightChild.bigOnLevel(lev) >= lev)
我得到二进制运算符错误错误的操作数类型> =第一类型T第二类型int。 但是,如果不让它们相互比较,我想不出另一种方法来找到具有最大价值的节点。
整个代码(末尾的方法):
public class BinarySearchTree<T extends Comparable<T>> {
private T content;
private BinarySearchTree<T> leftChild,rightChild;
public BinarySearchTree() {
content = null;
leftChild = null;
rightChild = null;
}
public T getContent() {
if (!isEmpty()) {
return content;
} else {
throw new RuntimeException();
}
}
public boolean isEmpty() {
return content == null;
}
public boolean isLeaf() {
return !isEmpty() && leftChild.isEmpty() && rightChild.isEmpty();
}
public void add(T t) {
if (isEmpty()) {
content = t;
leftChild = new BinarySearchTree<T>();
rightChild = new BinarySearchTree<T>();
} else {
if (content.compareTo(t) > 0) {
leftChild.add(t);
} else if (content.compareTo(t) < 0) {
rightChild.add(t);
}
}
}
public boolean contains(T t) {
if (isEmpty()) {
return false;
} else {
if (content.compareTo(t) > 0) {
return leftChild.contains(t);
} else if (content.compareTo(t) < 0) {
return rightChild.contains(t);
}
return true;
}
}
public int size() {
if (isEmpty()) {
return 0;
} else {
return 1 + leftChild.size() + rightChild.size();
}
}
public void show() {
if (!isEmpty()) {
leftChild.show();
System.out.println(content);
rightChild.show();
}
}
//Program:
public T bigOnLevel (int lev)
{
int currentlevel = 0;
if(isEmpty() || lev<0 )
{
return null;
}
else
{
if(currentlevel < lev)
{
currentlevel++;
if(!rightChild.isEmpty() && rightChild.bigOnLevel(lev) >= lev)
{
return rightChild.bigOnLevel(lev);
}
else
{
if(!leftChild.isEmpty() && leftChild.bigOnLevel(lev) >= lev)
{
return leftChild.bigOnLevel(lev);
}
else
{
return null;
}
}
}
else
{
return content;
}
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)