我有两个类,BSTSet和BSTNode,它们都有一个可以返回高度的height()方法。我得到一个stackoverflow错误,并不确定是什么导致它。返回二叉查找树的高度
BSTSet
public class BSTSet <E extends Comparable<E>> extends AbstractSet <E> {
// the root of the supporting binary search tree
private BSTNode<E> root;
// number of elements in the set
private int count = 0;
public boolean isEmpty() {
return count == 0;
}
public int size() {
return count;
}
public int height() {
if(root == null) return -1;
else return root.height();
}
}
BSTNode
public class BSTNode <E extends Comparable<E>> {
private E value;
private BSTNode<E> left;
public BSTNode<E> right;
public BSTNode(E value) {
this.value = value;
}
public E getValue() {
return value;
}
public BSTNode<E> getLeft() {
return left;
}
public BSTNode<E> getRight() {
return right;
}
public int height() {
if(left == null && right == null) return 0;
if(left != null && right == null) {UI.println("left");return left.height()+ 1; }
else if(right != null && left == null){UI.println("right");return right.height()+ 1;}
else{UI.println("both"); return Math.max(right.height(), left.height()) + 1;}
}
}
如果您想了代码或不再需要的信息,请随时提问。
不幸的是,我无法使用最多,但我修改了代码,得到它的工作,但我相信它不是返回正确的值.. – M0rty 2014-10-12 03:51:23