我有一棵BST树。我想创建一个获取值的方法,并返回包含它的值(root = 0)的节点的级别,没有这样的节点?返回-1。 我想递归地做。 这段代码很好用:
private int recursiveContains(BinaryNode node, int searchVal){
int nodeKey = node.nodeKey;
if (searchVal < nodeKey){
if (node.leftChild != EMPTY_NODE)
return 1 + recursiveContains(node.leftChild, searchVal);
}else if (searchVal > nodeKey){
if (node.rightChild != EMPTY_NODE)
return 1 + recursiveContains(node.rightChild, searchVal);
}
return 0;
}
但是,只要树包含搜索值。
当我到达一个叶子并没有找到值时,如何停止迭代并返回-1? 有可能recursivle吗?
由于
答案 0 :(得分:1)
您只需调整最终案例即可。现在,如果树中的值不是,则只返回将插入值的节点的深度,因为最后的情况只是return 0
。相反,您需要显式检查当前节点是否确实是正确的节点。如果是,您可以返回0
;否则你应该返回-1
。然后,递归调用需要查找该特殊值并适当地处理它。
我可能会在开始时进行这种明确的检查 - 这是所请求节点的基本情况。然后在最后,你的&#34;跌倒&#34; value(如果没有其他条件为真,则返回的值)为-1
。所以你最终得到这样的东西:
// WARNING: UNTESTED CODE
if (searchVal == nodeKey) {
return 0;
} else if (searchVal < nodeKey && node.leftChild != EMPTY_NODE) {
int childResult = recursiveContains(node.leftChild, searchVal);
if (childResult != -1) { // Only use the child result if the value was found.
return 1 + childResult;
}
} else if (searchVal > nodeKey && node.rightChild != EMPTY_NODE) {
int childResult = recursiveContains(node.rightChild, searchVal);
if (childResult != -1) { // Only use the child result if the value was found.
return 1 + childResult;
}
}
// If you haven't returned by now, the value can't be found along this path.
return -1;