首先是把声明函数放在调用函数前,产生bug
var result = Infinity;
var getDepth = function(node, depth) {
if (node.left == null && node.right == null) {
// result = depth > result ? result : depth
result = Math.min(result, depth)
return;
}
if (node.left) getDepth(node.left, depth+1)
if (node.right) getDepth(node.right, depth+1)
return;
}
var minDepth = function(root) {
if (root == null) return 0;
getDepth(root, 1);
return result;
};

然后是参考题解,把声明函数放在函数内,代码运行成功。
var minDepth = function (root) {
if (root == null) return 0;
var result = Infinity;
var getDepth = function (node, depth) {
if (node.left == null && node.right == null) {
// result = depth > result ? result : depth
result = Math.min(result, depth)
return;
}
if (node.left) getDepth(node.left, depth + 1)
if (node.right) getDepth(node.right, depth + 1)
return;
}
getDepth(root, 1);
return result;
};

具体原因,还没想明白,先记录一下,目前排除是代码逻辑问题,基本的思路是正确的,之后知道原因了再补充,或者有大佬明白可以指点一下吗?
文章探讨了在JavaScript中,将声明函数放在调用函数之前导致的错误,以及将函数声明移至函数内部以解决问题的解决方案。代码示例展示了一个计算树最小深度的函数minDepth,通过调整函数getDepth的声明位置,成功避免了bug并使代码正常运行。
1218

被折叠的 条评论
为什么被折叠?



