leetcode每天5题-Day44(二叉树4-深度)

1.二叉树的最大深度

104. 二叉树的最大深度-简单
b站-代码随想录

二叉树深度与高度区别:
深度:二叉树中任意一个节点到根节点的距离;(前序遍历)
高度:二叉树中任意一个节点到叶子节点的距离;(后序遍历)
题目关键:二叉树的最大深度就是根节点的高度

递归

var maxDepth = function(root) {
	//递归三部曲
	// 1. 确定递归函数的参数和返回值
    const getDepth = function(root) {
    	// 2. 确定终止条件
        if(!root) return 0;
        // 3.确定单层逻辑
        let leftHeight = getDepth(root.left);
        let rightHeight = getDepth(root.right);
        return 1 + Math.max(leftHeight, rightHeight);
    }
    return getDepth(root);
};

简洁版👇

var maxdepth = function(root) {
    if (root === null) return 0;
    return 1 + Math.max(maxdepth(root.left), maxdepth(root.right))
};

迭代(层序遍历)

2.N 叉树的最大深度

559. N 叉树的最大深度-简单

递归

var maxDepth = function(root) {
    if(!root) return 0
    let depth = 0
    for(let node of root.children) {
        depth = Math.max(depth, maxDepth(node))
    }
    return depth + 1
}

迭代(层序遍历)

3.二叉树的最小深度

111. 二叉树的最小深度-简单
b站-代码随想录

思路:和求最大深度差不多,也用后序遍历,只不过每次取节点的最小深度,本质上求的是根节点的最小高度。

递归

var minDepth1 = function(root) {
    if(!root) return 0;
    
    // 到叶子节点 返回 1
    if(!root.left && !root.right) return 1;
    
    // 只有右节点时 递归右节点
    if(!root.left) return 1 + minDepth(root.right);
    
    // 只有左节点时 递归左节点
    if(!root.right) return 1 + minDepth(root.left);
    
    return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
};

迭代

var minDepth = function(root) {
    if(!root) return 0;
    const queue = [root];
    let dep = 0;
    while(true) {
        let size = queue.length;
        dep++;
        while(size--){
            const node = queue.shift();
            // 到第一个叶子节点 返回 当前深度 
            if(!node.left && !node.right) return dep;
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值