Counting number of grandchildren in a tree [duplicate]
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;
}
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.
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:
- pass a
depth
(or equivalent) parameter recursively - maintain the count elsewhere (bad)
- assign each instance of the class a
myDepth
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)
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.
public int calcFactorial(int facnum){
int res;
if (facnum==1){
res=1;
}
else {
res=facnum*calcFactorial(facnum-1);
}
}
精彩评论