计算树上孙子的数量
可能的重复:
一定步数后停止递归
会出现什么问题用这里的方法来计算树中孙子的数量,但不计算曾孙的数量?
(child1 是左孩子,child2 是右孩子)此外,此方法不应采用任何参数。如果您提供替代解决方案,也请告诉我我当前的解决方案有什么问题。
public int countGrandChildren() // but not greatGrandChildren
{
int count=0;
int depth=1;
if (depth<4){
if (child1!=null){
count+=child1.countGrandChildren();
depth++;
if (depth==3)
count++;
}
if (child2!=null){
count+=child2.countGrandChildren();
depth++;
if (depth==3)
count++;
}
}
return count;
}
Possible Duplicate:
Stop recursion after a certain amount of steps
What would be wrong with this method here for counting the number of grandchildren in a tree, but not great grandchildren?
(child1 is left child and child2 is right child) Also, this method should not take any parameters. If you offer an alternative solution, please also tell me whats wrong with my current solution..
public int countGrandChildren() // but not greatGrandChildren
{
int count=0;
int depth=1;
if (depth<4){
if (child1!=null){
count+=child1.countGrandChildren();
depth++;
if (depth==3)
count++;
}
if (child2!=null){
count+=child2.countGrandChildren();
depth++;
if (depth==3)
count++;
}
}
return count;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果不将深度传递给每个递归调用,这将如何工作?深度在开始时始终为 1,然后您可以增加它。但它永远不会是 == 3。
How would this work if you don't pass depth to each recursion call? Depth is always 1 at start and then you may increment it. but it will never be == 3.
正如你之前的问题中已经讨论过的,你不是在连续的递归调用之间传递任何参数,那么它们怎么可能终止呢?
int 深度 = 1; if (深度 < 4) ...
将永远都是这种情况!解决方案是以下可能性之一的变体:
As already discussed at your previous question, you're not passing any parameters between successive recursive calls, so how could they possibly terminate?
int depth = 1; if (depth < 4) ...
will always be the case!The solutions are variations on one of the following possibilities:
depth
(or equivalent) parameter recursivelymyDepth
member variable at construction based on its position in the tree (this will be a pain if you ever need to rearrange items in the tree)最好的选择是将深度变量作为函数的参数传递,这是一个更简单的示例,通过递归调用函数但每次传递的参数减去 1 来计算数字的阶乘。
Your best option is to pass the depth variable as a parameter of the function here is a simpler example that calculates the factorial of a number by calling the function recursively but subtracting 1 from the argument passed each time.