作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这两个版本有什么区别?
public static int countLeaves(IntTreeNode root) {
if (root == null) {
return 0;
} else
return 1 + countLeaves(root.left) + countLeaves(root.right);
}
public static int countLeaves(IntTreeNode root) {
if (root == null) {
return 0;
} else if (root.left == null && root.right == null) {
return 1;
} else
return countLeaves(root.left) + countLeaves(root.right);
}
我在互联网上找不到任何使用第一个版本的东西。第一个版本有错吗?
我试着在纸上追踪它们,它们似乎是一样的。但我只是想确定一下。
最佳答案
第一个似乎计算树中的所有节点,而第二个似乎计算所有叶子。
事实上,在第一个中,当不再有有效的树( root == null
)时,递归就会停止,并且它总是通过添加 1
进入递归检查左树和右树。 (对于当前节点)。
第二个仅使用条件 if (root.left == null && root.right == null)
对叶子进行计数.
假设叶子被识别为具有 null
的节点root.left
和一个 null
root.right
。
关于java - 计算树中叶子的两种版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46993383/
我是一名优秀的程序员,十分优秀!