【问题标题】:Counting the number of leaves in a binary tree at a given level [closed]在给定级别计算二叉树中的叶子数[关闭]
【发布时间】: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


【解决方案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);
        }
    }

【讨论】:

    【解决方案2】:

    您的算法没有给出正确答案,因为一旦您的深度变为负数,它就不会停止在该特定深度并且仍然会进一步计算叶节点,您必须给出深度何时变为负数的额外条件(返回 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);
        }
    }
    
    

    【讨论】:

    • 您不必在负深度返回 0,但这是一个很好的优化。关键部分是&amp;&amp; depth == 0 位,它确保省略了不在正确深度的叶子。
    • @ggorlen - 哦,是的!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2016-01-17
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多