Day15|104.二叉树的最大深度、111.二叉树的最小深度

一、104.二叉树的最大深度

题目链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree/
文章链接:https://programmercarl.com/0104.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6.html#%E7%9B%B8%E5%85%B3%E9%A2%98%E7%9B%AE%E6%8E%A8%E8%8D%90
视频链接:https://www.bilibili.com/video/BV1Gd4y1V75u/

package com.fifteenday.tree;

//二叉树的最大深度
/**
 *  后序遍历求解高度(左右中);高度就是一层楼的高度
 *  前序遍历求救深度(中左右):深度就是一口井的深度
 *  二叉树的高度:是从叶子结点到根节点的距离
 *  二叉树的深度:是从根节点到叶子结点的距离
 *  高度 = 深度
 *  递归终止条件:if node == 0 ==> return 0;
 **/
public class BinaryTreeMaxDepth {

    public int maxDepth(TreeNode node){
        if (node==null){
            return 0;
        }
        int getLeftDepth = maxDepth(node.left);      //左
        int getRightDepth = maxDepth(node.right);   //右
        int depth = 1 + Math.max(getLeftDepth,getRightDepth);    //中
        return depth;
    }
}

解题思路
在这里插入图片描述

二、111.二叉树的最小深度

题目链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/
文章链接:https://programmercarl.com/0111.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E6%B7%B1%E5%BA%A6.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
视频链接:https://www.bilibili.com/video/BV1QD4y1B7e2/?vd_source=721f65ae0501389782be0dcb48a2c421

package com.fifteenday.tree;

/**
 *  二叉树最小深度
 *  解题思路:后序遍历(左右中)
 *  最小深度是从根节点到叶子节点的距离;注意:叶子节点是没有左右孩子的,null不能作为叶子节点
 *  回顾:递归的三大步骤:
 *      1、确定递归函数的参数和返回值
 *      2、确定终止条件
 *      3、确定单层递归的逻辑
 *
 */
public class BinaryTreeMinDepth {

    public int minDepth(TreeNode node){
        if (node==null) return 0;
        int leftDepth = minDepth(node.left);        //左
        int rightDepth = minDepth(node.right);      //右

        //中
        if (node.left==null){
            return rightDepth+1;
        }

        if (node.right==null){
            return leftDepth+1;
        }

        //左右节点都不为空的情况下,取最小值
        return 1+Math.min(leftDepth,rightDepth);

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值