![](/img/trans.png)
[英]I don't understand why I need to put two lines in a specific order for it to work (recursion)
[英]Don't understand why I need a return on the last lines
我正在解决有关找出树木中叶子的最小路径的问题。 我在C ++中将BFS与存储节点和当前深度的队列一起使用。
我遍历BFS中的树,并在前进时将节点添加到队列中。 一旦到达第一片叶子,我便退出循环。
我不明白为什么我需要添加返回值0; 程序末尾的行(在代码上有注释)。
如果我删除该行,则会收到一条错误消息,提示该函数已结束而没有返回。
我需要哪种情况?
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?
}
};
因为您在函数中有退出但不返回值的路径。 例如,如果depthQ为空,则您的代码将退出而不返回任何内容(但对于最后的“返回0”而言)。 并且您已经声明了要返回int的函数。 因此,所有代码路径都必须返回一些int。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.