Java 二叉搜索树中数据点深度的求法

Java 二叉搜索树中数据点深度的求法,java,recursion,binary-search-tree,Java,Recursion,Binary Search Tree,这是家庭作业。不要只发布代码 我需要在二叉搜索树中找到给定数据点的深度。我实现了一个depth方法和一个helper方法countNodes,它递归地对节点进行计数 如果我们搜索的数据在树中不存在,我需要返回-1。考虑到我的递归,我不认为这是可能的 @Override public int depth(T data) { if (data == null) { throw new IllegalArgumentException("Data is null");

这是家庭作业。不要只发布代码

我需要在二叉搜索树中找到给定数据点的深度。我实现了一个depth方法和一个helper方法countNodes,它递归地对节点进行计数

如果我们搜索的数据在树中不存在,我需要返回-1。考虑到我的递归,我不认为这是可能的

@Override
public int depth(T data) {
    if (data == null) {
        throw new IllegalArgumentException("Data is null");
    }
    //FIXME don't use the contains() method
    return countNodes(root, data);
}

/**
 * Helper method counts teh nodes
 * @param  node the node we're going to start counting at
 * @param  data that we're looking for
 * @return the sum of the number of children nodes
 */
private int countNodes(BSTNode<T> node, T data) {
    if (node == null) {
        return 0;
    }
    if (compare(data, node.getData()) == 0) {
        return 1;
    } else if (compare(data, node.getData()) < 0) {
        return 1 + countNodes(node.getLeft(), data);
    } else if (compare(data, node.getData()) > 0) {
        return 1 + countNodes(node.getRight(), data);
    } else {
        return -1;
    }
}

这种情况下的一般想法是将未找到状态(在本例中为-1)备份递归树。您可以通过检查递归调用是否返回-1来完成此操作。如果返回-1,则返回到调用堆栈的顶部,如果返回不返回,则继续正常操作。

您必须检查递归函数是否返回-1,如果返回,则返回-1。@lared是否需要将该检查放入递归方法中?或者在标准方法中?在递归方法中,否则您会覆盖它IIRC您刚才在那里添加了1。您必须考虑递归调用函数的每一行,在else ifs中也是如此,因为当函数必须首先返回-1时,-1必须传播UPPLESE note,就像在最深处一样。