gpt4 book ai didi

java - 计算树中叶子的两种版本

转载 作者:行者123 更新时间:2023-12-02 02:31:40 24 4
gpt4 key购买 nike

这两个版本有什么区别?

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com