【发布时间】:2013-03-12 21:55:24
【问题描述】:
所以我正在研究一种获取二叉搜索树中节点数的方法,当我有 3 个节点时,它给我 3,但如果我做 5 它给我 4,我需要改变什么?
int BinaryTree::size(int count, Node *leaf) const
{
if(leaf != NULL)//if we are not at a leaf
{
size(count + 1, leaf->getLeft());//recurisvly call the function and increment the count
size(count + 1, leaf->getRight());
}
else
{
return count;//return the count
}
}
【问题讨论】:
-
要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或添加打印语句)来隔离问题,方法是跟踪程序的进度,并将其与您期望发生的情况进行比较。一旦两者发生分歧,那么您就发现了您的问题。 (然后如果有必要,你应该构造一个minimal test-case。)
-
您在
if的真实分支中缺少返回语句 -
if语句的第一个块中没有返回值。你要返回什么值?