【发布时间】:2020-05-08 19:47:20
【问题描述】:
我正在尝试计算某个级别的叶子数量(按深度给出),但由于某种原因,我不明白为什么它不起作用。 有人有更好的建议吗? 请看下面我的代码:
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);
}
}
【问题讨论】:
-
depth是干什么用的? -
在第二个条件中你有 AND
&&不应该是 OR|| -
@Boken 实际上,我认为这是正确的。 if 判断它是否是叶子,所以它返回 1。
-
与您的问题无关我建议您将
root重命名为node。 -
您没有深度
标签: java tree binary binary-tree binary-search-tree