Java 在给定级别计算二叉树中的叶子数
我试图在一定程度上(根据深度)计算树叶的数量,但出于某种原因,我不明白为什么它不起作用。 有人有更好的建议吗? 请看下面我的代码:Java 在给定级别计算二叉树中的叶子数,java,tree,binary,binary-tree,binary-search-tree,Java,Tree,Binary,Binary Tree,Binary Search Tree,我试图在一定程度上(根据深度)计算树叶的数量,但出于某种原因,我不明白为什么它不起作用。 有人有更好的建议吗? 请看下面我的代码: public static int countLevel(TreeNode root, int depth) { if (root == null) { return 0; } else if (root.left == null && root.right == null) { return 1;
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);
}
}
publicstaticintcountlevel(treenoderoot,intdepth){
/*优化
如果(depthWhat是depth
for?在第二个条件中,您拥有并且&
不应该是或|
@Boken实际上,我认为这是正确的。如果确定它是否是一个叶,那么它返回1。与您的问题无关,我建议您在节点中重命名根。深度没有返回条件<0.另外,您不需要使用'else'子句,因为返回的是true。您不必在负深度处返回0,但这是一个很好的优化。关键部分是&&depth==0
位,它确保忽略深度不正确的叶子。@ggorlen-哦,是的!谢谢。