不明白为什么我在最后几行需要 return

Don't understand why I need a return on the last lines

我正在解决一个关于找出树中一片叶子的最小路径的问题。我在 C++ 中使用 BFS,队列存储节点和当前深度。

我遍历 BFS 中的树,在我前进的过程中将节点添加到我的队列中。一到达我的第一片叶子,我就退出循环。

我不明白为什么我需要添加 return 0;程序末尾的行(注释代码)。

如果我删除该行,我会收到一条错误消息,指出函数在没有 return 的情况下结束。

在什么情况下我需要它?

class TreeDepth{
    TreeNode* node;
    int depth;
    public:
    TreeDepth(int depth, TreeNode* node): depth(depth), node(node) {}
    TreeNode* getNode() {return node;}
    int getDepth() {return depth;}
};
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root)
            return 0;
        else
        {
            std::queue<TreeDepth> depthQ;
            TreeDepth nodeDepth(1,root);
            depthQ.push(nodeDepth);
            while(!depthQ.empty())
            {
                TreeDepth currentNode = depthQ.front();
                depthQ.pop();
                if(!currentNode.getNode()->left && !currentNode.getNode()->right)
                    return currentNode.getDepth();
                else
                {
                    if(currentNode.getNode()->left)
                    {
                        TreeDepth leftNodeDepth(currentNode.getDepth() + 1, currentNode.getNode()->left);
                        depthQ.push(leftNodeDepth);
                    }
                    if(currentNode.getNode()->right)
                    {
                        TreeDepth rightNodeDepth(currentNode.getDepth() + 1, currentNode.getNode()->right);
                        depthQ.push(rightNodeDepth);
                    }
                }
            }
        }
    return 0; // why do I need this line?
    }
};

因为您在函数中有退出但没有 return 值的路径。例如,如果 depthQ 是空的,你的代码将在没有 returning 任何东西的情况下退出(除了最后的 'return 0')。并且您已将函数声明为 return 一个 int。所以所有的代码路径必须 return 一些 int.