Java-计算给定级别的二叉树中的叶子数

问题描述 投票:0回答:2

我正在尝试计算某个级别(按深度给出)的叶子数量,但是由于某种原因,我不明白为什么它不起作用。有人有更好的建议吗?请在下面查看我的代码:

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);
    }
}
java tree binary binary-tree binary-search-tree
2个回答
2
投票

也许您想要这个

这里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
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.