返回值存储在哪里,以及如何/可以递增



我已经做了相当多的阅读和研究,但我仍然没有100%理解。对于";"二进制树的最小深度";,在递归函数中有多个返回的想法正在扼杀我;最小深度";正在增加,我知道这可能与我对返回语句工作的误解有关。请帮忙,谢谢。

int minDepth(Node *root) {
if(!root) return 0;

if(!root->left) return 1 + minDepth(root->right);


if(!root->right) return 1 + minDepth(root->left);

return 1+min(minDepth(root->left),minDepth(root->right));
}

如果有帮助,从逻辑上讲,上面的内容也可以写成

int minDepth(Node *root) {
int result;
if(!root) 
result = 0;
else if(!root->left) 
result = 1 + minDepth(root->right);
else if(!root->right) 
result = 1 + minDepth(root->left);
else
result = 1 + min(minDepth(root->left), minDepth(root->right));
return result;
}

最新更新