关于使用队列,对二叉树进行广度优先遍历(BFS)算法,求解二叉树最小深度的问题,
有一个代码上的问题:
算法如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        int res = 1;
        Queue<TreeNode> queue = new LinkedList<>();
        queque.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode temp = queue.poll();
                if (temp.left == null && temp.right == null) return res;
                if (temp.left != null) {
                    queue.offer(temp.left);
                }
                if (queue.right != null) {
                    queue.offer(temp.right);
                }
            }
            res++;
        }
        return res;
}
我的问题在倒数第二行
return res;
因为根据算法,进行二叉树遍历时候,一定能找到一个点的左右子节点都是null,并在26行:
                if (temp.left == null && temp.right == null) return res;
进行返回。
实际进行代码测试时,也印证了我的想法,因为我无论return res, return 200,还是return 1000。都可以通过代码测试.
但是如果不加这个return,会显示error: missing return statement
我不理解的是,代码一定不会运行到最后return这一行,为什么系统还是会报错需要加上return?