问题
I'm looking to take some code I've written in Java for a binary tree class and remove the count parameter from the arguments, but keep the whole thing recursive.
So, given a class with these variables:
public class BinaryTree<E> {
protected E data;
protected BinaryTree<E> left,right;
How could I do that for:
public int levelCount(int count, int level){
if (data == null) {return 0;}
if (count == level) {return 1;}
else {
return this.getRight().levelCount(count+1,level) + this.getLeft().levelCount(count+1,level);
}
}
This should (and does) return the number of nodes at any given level of the binary tree.
So with a tree "thatTree" which looks like:
2
/ \
6 3
/ \ / \
4 5 7 10
thatTree.levelCount(0) returns 1, thatTree.levelCount(1) returns 2, thatTree.levelCount(2) returns 4
回答1:
Why not pass a single argument, subtract 1 on each recursion, and end when it is 0? Something like:
public int levelCount(int level){
if (data == null || level < 1) {return 0;}
if (level == 1) {return 1;}
else {
return this.getRight().levelCount(level-1) + this.getLeft().levelCount(level-1);
}
}
来源:https://stackoverflow.com/questions/26620908/binary-tree-method-to-recursively-count-the-number-of-nodes-on-a-level-without