我想计算某一层的叶子数量(由深度给定),但由于某些原因,我不明白为什么它不会工作。
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) {
/* optimization
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);
}
}