在java中查找二进制搜索树中特定节点的深度

时间:2015-02-08 01:37:21

标签: java binary-search-tree depth

如果我得到了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。

0 个答案:

没有答案