查找二叉搜索树的最小深度时的附加 return 语句

Additional return statement while finding minimum depth of a Binary Search Tree

以下是我在网上找到的求二叉搜索树最小深度的代码:

public class Solution {
public int minDepth(TreeNode root) {
    if(root == null){
        return 0;
    }

    LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
    LinkedList<Integer> counts = new LinkedList<Integer>();

    nodes.add(root);
    counts.add(1);

    while(!nodes.isEmpty()){
        TreeNode curr = nodes.remove();
        int count = counts.remove();

        if(curr.left != null){
            nodes.add(curr.left);
            counts.add(count+1);
        }

        if(curr.right != null){
            nodes.add(curr.right);
            counts.add(count+1);
        }

        if(curr.left == null && curr.right == null){
            return count;
        }
    }

    return 0;
}

}

我不明白的是最后的额外return语句- return 0。为什么需要这个?

这是针对根不为空的情况,但它是树中唯一的节点(根在深度 0 处)。 return 语句是必需的,因为如果树为空,则必须 returned。它returns 0,因为深度为0。

与 ghostofrasputin 类似,return 语句存在是因为如果 while 条件不满足,那么 return 仍然有一个值。

现在更重要的问题是,如果程序永远不会到达那个 return 语句,为什么我们需要最后一个 return? (我认为这是这种情况)

即使您可以判断不会使用 return 语句,编译器还不够复杂,无法确定这一点,因此它需要一个 return 语句以防 while 循环退出。

类似于下面的代码

public boolean getTrueOrFalse() {
    if(Math.random() < 1) {
        return true;
    }

    return false;
}

虽然我们知道这将始终 return 为真,因为 Math.random() 总是小于 1,但编译器无法计算出这一点,因此 return 语句是如果不满足 if 语句,则需要。