我有兩個類,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