【发布时间】:2014-04-24 01:26:23
【问题描述】:
所以我正在使用二叉搜索树,我遇到的一种方法是一种名为stickCt 的方法,它基本上会计算树中的棒数并返回数字。为了让它成为一根棍子,它必须有一个 null 和一个非 null 子节点才能被视为一根棍子,我已经完成了我的代码并且它符合但我一直得到 0 作为我的返回值,我不知道出了什么问题我已经尝试过移动东西,但似乎没有任何帮助,我们将不胜感激。顺便说一下,我是递归的,这里是代码:
// The number of nodes with exactly one non-null child
//driver
public int stickCt () {
return stickCt(root);
}
private static int stickCt (IntNode T) {
int num;
//easiest case
if (T == null) {
num = 0;
}
//if the left child is null and the right child is not null
else if (T.getLeft() == null && T.getRight() != null) {
num = stickCt(T.getRight()) + 1;
}
//if right child is null and left side is not null
else if (T.getRight() == null && T.getLeft() != null) {
num = stickCt(T.getLeft()) + 1;
}
//recursive part
else {
num = stickCt(T.getLeft()) + stickCt(T.getRight());
}
return num;
}
【问题讨论】:
-
这里的递归逻辑看起来不错。你在什么树上测试这个?
-
虽然我很高兴下面的答案对您有所帮助,但我担心您还没有真正确定您遇到问题的根本原因。新代码有效吗?如果是这样,您能否尝试找出为什么您的原始代码没有这样我们可以看到哪里出了问题?
标签: java algorithm data-structures binary-search-tree