在二进制搜索树中查找数据点的深度

时间:2015-02-09 22:47:01

标签: java recursion binary-search-tree

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

我需要在二叉搜索树中找到给定数据点的深度。我已经实现了一个depth()方法和一个帮助方法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 个答案:

答案 0 :(得分:0)

在这种情况下的一般想法是带来未找到的#34; status,在本例中为-1,备份递归树。您可以通过检查递归调用是否返回-1来执行此操作 - 如果是,则将-1返回到调用堆栈的顶部,如果不是,则按正常方式继续。

相关问题