我正在尝试计算某个级别(按深度给出)的叶子数量,但是由于某种原因,我不明白为什么它不起作用。有人有更好的建议吗?请在下面查看我的代码:
public static int countLevel(TreeNode root, int depth) {
if (root == null) {
return 0;
} else if (root.left == null && root.right == null) {
return 1;
} else {
return countLevel(root.left, depth - 1) + countLevel(root.right, depth - 1);
}
}
也许您想要这个
这里desireDepth
是您要计算树叶数的特定深度,而depth
是当前深度。
public static int countLevel(TreeNode root, int desireDepth ,int depth) {
if (root == null) {
return 0;
} else if (root.left == null && root.right == null && depth == desireDepth) {
return 1;
} else {
return countLevel(root.left, desireDepth, depth + 1) + countLevel(root.right, desireDepth, depth + 1);
}
}
您的算法没有给出正确的答案,因为一旦您的深度变为负数,它就不会停止在该特定深度,而是继续前进并计算叶节点,您必须给出一个额外的条件,当深度变为负数(返回0)] >
解决方案的修改版:
public static int countLevel(TreeNode root, int depth) {
if(depth<0)
return 0;
if (root == null) {
return 0;
} else if (root.left == null && root.right == null && depth==0) {
return 1;
} else {
return countLevel(root.left, depth - 1) + countLevel(root.right, depth - 1);
}
}