二叉树最小深度/最大深度

 

 

 

求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。

求给定二叉树的最大深度。最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。

// 最小深度
/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return int整型
  */
function run( root ) {
    // write code here
    if(!root) {return 0}
    const queue = [root]
    let depth = 0
    let len = 0
    while(len = queue.length){
        depth++
        for(let i=0;i<len;i++){
            const node = queue.shift()
            if(!node.left&&!node.right) return depth;
            if(node.left) queue.push(node.left)
            if(node.right) queue.push(node.right)
        }
    }
}
module.exports = {
    run : run
};




//最大深度
/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return int整型
  */
function maxDepth( root ) {
    if(!root) return 0
    let stack = [root]
    let depth = 0
    let len = 0
    while(len = stack.length){
        depth++
        for(let i=0;i<len;i++){
            let node = stack.shift()
            if(node.left) stack.push(node.left)
            if(node.right) stack.push(node.right)
        }
    }
    return depth
}

function maxDepth( root ) {
    // write code here
    if (root)  {
        return Math.max(maxDepth( root.left ), maxDepth( root.right )) + 1;
    } else {
        return 0;
    }
     
}
module.exports = {
    maxDepth : maxDepth
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值