首页 > 其他分享 >leetcode-111-easy

leetcode-111-easy

时间:2022-11-30 21:45:35浏览次数:46  
标签:right depth minDepth 111 easy null root leetcode left

Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
Constraints:

The number of nodes in the tree is in the range [0, 105].
-1000 <= Node.val <= 1000

思路一:假设给定的节点不为空,那么完全分类后有四种情况

  • left == null && right == null
  • left != null && right != null
  • left == null && right != null
  • left != null && right == null

其中只有第一种情况是符合题目的叶子节点,递归判断即可

public int minDepth(TreeNode root) {
    if (root == null) return 0;
    return minDepth(root, 1);
}

public int minDepth(TreeNode root, int depth) {
     if (root.left == null && root.right == null) {
        return depth;
    } else if (root.left != null && root.right == null) {
        return minDepth(root.left, depth + 1);
     } else if (root.right != null && root.left == null) {
         return minDepth(root.right, depth + 1);
     } else {
         return Math.min(minDepth(root.left, depth + 1), minDepth(root.right, depth + 1));
     }
}

思路二:官方给的题解是从底层往上递归,代码可以更简洁

标签:right,depth,minDepth,111,easy,null,root,leetcode,left
From: https://www.cnblogs.com/iyiluo/p/16939842.html

相关文章

  • 力扣 leetcode 162. 寻找峰值
    问题描述峰值元素是指其值严格大于左右相邻值的元素。给你一个整数数组nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即......
  • 力扣 leetcode 153. 寻找旋转排序数组中的最小值
    问题描述已知一个长度为n的数组,预先按照升序排列,经由1到n次旋转后,得到输入数组。例如,原数组nums=[0,1,2,4,5,6,7]在变化后可能得到:若旋转4次,则可以得到[4......
  • 力扣 leetcode 33. 搜索旋转排序数组
    问题描述整数数组nums按升序排列,数组中的值互不相同。在传递给函数之前,nums在预先未知的某个下标k(0<=k<nums.length)上进行了旋转,使数组变为[nums[k],nums[k......
  • 力扣 leetcode 895. 最大频率栈
    问题描述设计一个类似堆栈的数据结构,将元素推入堆栈,并从堆栈中弹出出现频率最高的元素。实现FreqStack类:FreqStack()构造一个空的堆栈。voidpush(intval)将一......
  • IDEA使用EasyCode插件
    1、目的快速生成controller、mapper、service、serviceImpl、mappers.xml文件2、安装EasyCode插件File|Settings|Plugins搜索EasyCode,点击安装即可。3、配置模板......
  • 常用功能系列---【使用EasyCaptcha快速生成验证码】
    使用EasyCaptcha快速生成验证码1.引入pom坐标<!--验证码--><dependency><groupId>com.github.whvcse</groupId><artifactId>easy-captcha</artifactId>......
  • easylogging++的那些事(四)源码分析(二)日志记录宏(四)VERBOSE日志宏
    目录CVLOG宏宏展开源码剖析CVLOG_EVERY_N宏宏展开源码剖析CVLOG_AFTER_N宏宏展开源码剖析CVLOG_N_TIMES宏宏展开源码剖析VLOG宏DCVLOG宏DVLOG宏VLOG_EVERY_N宏VLOG......
  • [LeetCode] 1207. Unique Number of Occurrences
    Givenanarrayofintegers arr,return true ifthenumberofoccurrencesofeachvalueinthearrayis unique,or false otherwise.Example1:Input:arr......
  • 初次邂逅 EasyExcel
    前言由于工作原因,有这种需求,就是把数据库中的数据导出成Excel表格,同时,也得支持人家用Excel表格导入数据到数据库。当前项目也是在用EasyExcel,所以我不得不学啦!以前......
  • #yyds干货盘点# LeetCode程序员面试金典:URL化
    题目:URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以......