如果我得到了int深度方法(T数据),我被要求在二叉搜索树中找到其相应深度的深度。 我尝试了如下代码,但它不起作用:
public int depth(T data) {
if (data == null) {
throw new Exception();
} else {
if (!contains(data)) {
return -1;
} else {
return depth(root, data);
}
}
}
private int depth(BSTNode<T> processingNode, T data) {
if (processingNode.getData().compareTo(data) < 0) {
return 1 + depth(processingNode.getRight(), data);
} else if (processingNode.getData().compareTo(data) > 0) {
return 1 + depth(processingNode.getLeft(), data);
} else {
return 1;
}
}
似乎递归不起作用,因为返回值始终为1。