二叉树的深度_十七:二叉树的最小深度

e0194e96442548738ae82913ab76bf29.png

二叉树的最小深度: 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最短路径的长度为树的最小深度。

算法一

/** * @description 二叉树最小深度 * @param {*} root 二叉树 */function binaryTreeMinDepth(root) {    // 节点不存在时返回长度为0    if (!root) return 0    // 当节点存在时但是左右子节点不存在,返回长度为1    if (!root.left && !root.right) return 1    // 当左节点不存在,右节点存在,递归求出右节点深度,并加1    if (!root.left) return binaryTreeMinDepth(root.right) + 1    // 当右节点不存在,右节点存在,递归求出左节点深度,并加1    if (!root.right) return binaryTreeMinDepth(root.left) + 1    // 当左右节点都存在时 递归求出左右节点深度,毕竟求出左右节点深度最小值加1    return Math.min(binaryTreeMinDepth(root.right), binaryTreeMinDepth(root.left)) + 1}

算法二

/** * @description 二叉树最小深度 * @param {*} root 二叉树 */function binaryTreeMinDepth(root) {    // 根节点不存在时返回长度为0    if (!root) return 0    // 根节点存在深度为1    let depth = 1    // 声明一个队列默认存放根节点    const queue = [root]    while (queue.length) {        const len  = queue.length        // 遍历栈求出最小深度        for (let i = 0; i < len; i++) {            // 取出栈尾            const current = queue.shift()            // 如果遇到左右节点都不存在直接返回深度            if (!current.left && !current.right) return depth            // 如果左节点存在入栈            if (current.left)  queue.push(current.left)            // 如果右节点存在入栈            if (current.right)  queue.push(current.right)        }        // 深度加1        ++depth    }    // 如果找不到最小深度 则返回-1    return -1}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值