这是作业。不要只发布代码。
我需要在二叉搜索树中找到给定数据点的深度。我已经实现了一个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;
}
}
答案 0 :(得分:0)
在这种情况下的一般想法是带来未找到的#34; status,在本例中为-1
,备份递归树。您可以通过检查递归调用是否返回-1
来执行此操作 - 如果是,则将-1
返回到调用堆栈的顶部,如果不是,则按正常方式继续。