leetcode第111题最小深度,前序遍历,js声明函数放在函数前和函数内导致bug问题,未明白原因?

文章探讨了在JavaScript中,将声明函数放在调用函数之前导致的错误,以及将函数声明移至函数内部以解决问题的解决方案。代码示例展示了一个计算树最小深度的函数minDepth,通过调整函数getDepth的声明位置,成功避免了bug并使代码正常运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先是把声明函数放在调用函数前,产生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;

};

具体原因,还没想明白,先记录一下,目前排除是代码逻辑问题,基本的思路是正确的,之后知道原因了再补充,或者有大佬明白可以指点一下吗? 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值