【发布时间】:2015-08-15 08:43:54
【问题描述】:
我已经实现了使用递归查找二叉树大小的函数(参考一本关于数据结构和算法的书)
sn-p 代码如下:
// Returns the total number of nodes in this binary tree (include the root in the count).
public static int size(BinaryTreeNode root) {
int leftCount = root.left == null ? 0 : size(root.left);
int rightCount = root.right == null ? 0 : size(root.right);
return 1 + leftCount + rightCount;
}
而且它也有效。 但是我无法理解 leftCount 和 rightCount 元素是如何在递归函数调用之间增加的?不应该像下面这样:
// Returns the total number of nodes in this binary tree (include the root in the count).
public static int size(BinaryTreeNode root) {
int leftCount = 0;
int rightCount = 0;
leftCount = leftCount + (root.left == null ? 0 : size(root.left));
rightCount = rightCount+ (root.right == null ? 0 : size(root.right));
return 1 + leftCount + rightCount;
}
由于某种原因,对于下面的二叉树,这两个函数产生相同的结果(7,这是正确的)。
【问题讨论】:
-
您的第二个版本与第一个版本完全相同-您不会神奇地多次调用
size(root.left)(并且正确)-您调用它一次,但是当您调用相同的函数时再次,它被称为递归 - 想象一下你正在调用这个函数的一个新实例(使用其他参数等)......所以当你最终调用它第二个,第三个,......时间root当然@ 987654327@ 将发生变化,leftCount将是一个新变量(顺便说一句:这会破坏更大的树的堆栈) -
Carsten,正如我的问题所说,我理解它是一个递归调用。我的问题是为什么选项 1 有效。如果递归调用就像内存中的不同方法调用一样,返回值是如何添加的?
-
无意冒犯,但我认为您实际上并不了解它是如何工作的 - 返回值得到返回,然后您将它们添加到最后一行
-
让我们看看你的例子:首先是
root = 1(节点不是数字——我希望你明白)然后你计算size (2)next(再次是节点)——现在你得到一个新的带有root=2的实例现在就在你身边调用size(4),这里没有左/右孩子,所以你返回return 1+0+0,你最终进入root=2的实例 - 现在你做size(5) = 1+0+0,最后是@ 987654336@ ...与size(3)相同,最后size(1) = 1+3+3为您的最终答案.... -
@Carsten 没有冒犯。我是来学习的。你的第三条评论很有帮助。尽管经过几次尝试,我还是在纸上做了同样的事情。你能把你的解释作为答案吗?这对其他人也有帮助。
标签: recursion data-structures binary-tree