力扣111. 二叉树的最小深度

在这里插入图片描述
思路:后序遍历左右中,但与最大深度细节上有大不同:
1、左右有一个为空时,取不为空的最小高度
2、都不为空时,对比左右深度取最小;
3、都为空时取0,可忽略;

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        int ans = 1;
        int leftDep = minDepth(root.left); //左
        int rightDep = minDepth(root.right); //右
        //中,左右有一个为空,取不为空的一边的最小高度
        if(root.left==null && root.right!=null) { 
            ans += rightDep;
        }
        if(root.left != null && root.right == null) {
            ans += leftDep;
        }
        //都为空时是0,都不为空时,取最小深度
        ans += Math.min(leftDep, rightDep);

        return ans;
    }
}

相关推荐

  1. 0111——深度

    2024-04-21 20:04:03       64 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-21 20:04:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-21 20:04:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-21 20:04:03       82 阅读
  4. Python语言-面向对象

    2024-04-21 20:04:03       91 阅读

热门阅读

  1. EXCEL VBA限制工作数据批号或者自定义规则完整

    2024-04-21 20:04:03       36 阅读
  2. 给你的 vscode 扩展增加测试设置

    2024-04-21 20:04:03       36 阅读
  3. Golang的[]interface{}为什么不能接收[]int?

    2024-04-21 20:04:03       30 阅读
  4. Python设计模式

    2024-04-21 20:04:03       33 阅读
  5. Qwen量化脚本run_gptq.py解析

    2024-04-21 20:04:03       36 阅读
  6. 【回溯】Leetcode 131. 分割回文串【中等】

    2024-04-21 20:04:03       40 阅读