LeetCode算法题-Minimum Depth of Binary Tree(Java实现)

【文献阅读:信道估计】Deep Residual Learning Meets OFDM Channel Estimation 基于深度学习的信道估计技术 阅读详情

这是悦乐书的第168次更新,第170篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第27题(顺位题号是111)。给定二叉树,找到它的最小深度。最小深度是沿从根节点到最近的叶节点的最短路径上的节点数。叶子节点是没有子节点的节点。例如:

给定二叉树[3,9,20,null,null,15,7],

       3
      /  \
     9   20
        /  \
       15   7

返回其最小深度= 2。

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

之前我们有解过最大深度的题,今天这道题相反,求最短路径,那是不是直接将原来代码中的最大改为最小即可?如果你这样试过,会发现根本不是那么回事!

特殊情况一:当传入的二叉树为空时,最短路径就是0。

特殊情况二:当传入的二叉树只有根节点时,最短路径是1.

正常情况:当某一节点的左子节点为空时,这时我们需要求其右子节点的最短路径;当某一节点的右子节点为空时,这时我们需要求其左子节点的最短路径;当某一节点的左子节点和右子节点都不为空时,这时我们要求其左子树和右子树的最短路径。

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

03 第二种解法

除了上面的递归外,我们依旧可以使用遍历的方法。此解法与求最大深度时的第三种解法类似,也是利用队列,只是多了一步判断:当左右节点都为空时,此节点是叶子节点,需要更新最短路径的值。

public int minDepth2(TreeNode root) {
    if (root == null) {
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    int minDepth = Integer.MAX_VALUE;
    int depth = 1;
    while (!queue.isEmpty()) {
        int size = queue.size(); 
        while (size > 0) {
            TreeNode t = queue.poll();
            if (t.left != null) {
                queue.offer(t.left);
            }
            if (t.right != null) {
                queue.offer(t.right);
            }
            if (t.left == null && t.right == null) {
                minDepth = Math.min(minDepth, depth); 
            }
            size--;
        }
        depth++;
    }
    return minDepth;
}

04 小结

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

YOLOv13改进策略【Head】| (独家改进)结合 ICME-2024 中的PPA注意力模块,自研带有注意力机制的小目标检测头 本文记录的是利用PPA (并行补丁感知注意模块)改进YOLOv13的检测头。通过改进传统卷积,形成带有注意力机制的小目标检测头,使模型能够更好地关注小目标的重要信息。HCF-Net: Hierarchical Context Fusion Network for Infrared Small Object Detection采用多分支特征提取策略,通过不同分支提取不同尺度和层次的特征。利用局部、全局和串行卷积分支,对输入特征张量进行处理。通过控制 patch size参数实现局部和全局分支的区分,计算非重叠 阅读详情

相关推荐

stm32cubeMX使用HAL库点亮LED流水灯

目录

weixin_46129506的博客 3799

leetcode Minimum Depth of Binary Tree(Java)

题目: leetcode-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 nea...

聚沙成塔 356

射频接收机本振相噪指标计算:从倒易混频到GSM实战

在射频接收机设计中,相位噪声是衡量本振信号频谱纯度、影响系统灵敏度的关键指标。其核心影响机制源于倒易混频原理:当不纯净的本振信号与强带外阻塞信号混频时,本振的噪声边带会被转换到中频通带内,从而抬升接收机噪声基底。这一过程直接决定了接收机在阻塞测试等场景下的性能极限。从技术价值看,精确计算本振相噪要求,是进行系统噪声预算、实现成本与性能权衡的核心依据。尤其在手机、基站等对灵敏度要求极高的应用中,它指导着锁相环和压控振荡器的选型与设计。本文以经典的GSM DCS1800标准为例,通过详细的公式推导与变量分析,演

weixin_30368405的博客 329

leetcode-java-111. Minimum Depth of Binary Tree

/* 最小深度就是根节点到最近叶子节点的路径长度 和找二叉树的最大深度类似,但是区别如下: 递归终止条件: 1.根节点为null时,返回0 2.根节点左右都null时,返回1 3.大返回终止条件:返回较小值+1 但是需要注意的是: 这样就无法保证root是否是叶子节点了, */ public class Solution { public int minDepth(TreeNode

王欢的博客 1134

整理的15个公开且可直接使用的电力视觉输电线路领域数据集

而巡检数据是目前来说影响我们做科研的最大阻碍,为此本内容主要总结了,现有的且公开免费的巡检数据集,供大家使用。STN PLAD数据集133个航拍图像,五个电力部件:电力塔及其塔的ID、绝缘子,防震锤,联板(yoke),图像的尺寸在5472×3648到5472×3078。IDID数据集:2000张图像,包含三个类别,正常绝缘子,破损绝缘子和闪络绝缘子三个类别,用于目标检测的实验。TTPLA数据集,用于实例分割,1100张尺寸为3840×2160,包含两个类别,电力杆塔和电力线。主要用于电力杆塔的目标检测。

weixin_42048361的博客 5019

CrossOver实战:在Mac上流畅运行《梦幻西游》端游与搬砖指南

在跨平台应用开发与系统兼容性领域,如何让为特定操作系统设计的软件在其他平台上运行,是一个经典的技术挑战。其核心原理在于通过兼容层或转译技术,将程序的系统调用和图形接口指令实时转换为目标系统能理解的格式。这项技术的价值在于极大地扩展了硬件设备的软件生态,让用户无需依赖虚拟机或双系统即可无缝使用关键应用。在游戏、专业工具等场景中,这能显著提升工作效率和用户体验。本文以经典端游《梦幻西游》为例,详细解析如何在搭载Apple Silicon或Intel芯片的Mac上,借助CrossOver这一成熟的兼容层方案,构建

weixin_30129025的博客 574

【leetcode】Minimum Depth of Binary Tree 二叉树的最小深度 (JAVA)

求二叉树的最小深度,可以通过深度优先搜索DFS。/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public cl...

jake_xiao的博客 296

【Unity Shader】Special Effects(十二)Glow 外发光(UI)

Properties_GlowColor ("外发光颜色", Color) = (0, 0, 0, 1)_GlowIntensity("外发光强度", Range(0, 1)) = 1参数详解:_GlowColor:外发光颜色,指定外发光的显示颜色。_GlowIntensity:外发光强度,指定外发光的显示强度,0为不可见,1为最强强度。

神码编程 942

[leetcode]111. Minimum Depth of Binary Tree@Java解题报告

https://leetcode.com/problems/minimum-depth-of-binary-tree/description/ Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from

zjkC050818的博客 468

【电机应用控制】——直流有刷电机&驱动板/编码器介绍&PID算法&实操代码思路

声明:学习笔记来自正点原子B站教程,仅供学习交流!!玩具车、平衡车、无人机、印刷机、打印机、手机振动马达等电机即电动机(motor),也叫作马达,电能转化为机械能。按电源:直流、交流按用途:驱动用、控制用按运转速度:高速、低速、恒速、调速直流电机(有刷、无刷)、舵机、步进电机、伺服电机1、直流有刷电机(Brushed DC Motor,简称BDC)是内含电刷装置的将直流电能转化为机械能的电动机。例如四驱赛车四个马达操控方便、成本低、维护时换电刷即可;

weixin_51658186的博客 2万+

基于STM32设计的老人防摔倒报警设备(OneNet)_65

本文设计了一种基于STM32单片机的智能老人防摔倒报警设备。该系统结合MPU6050陀螺仪传感器实时监测老人的姿态变化,检测摔倒事件;通过SIM800C通信模块发送短信通知紧急联系人,并将GPS定位信息上传至云端平台,确保家属能够及时了解老人的准确位置。

1万+

leetcode 31: 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. 1. different from maximum depth. i

西施豆腐渣 2277

GPU硬件架构与微架构深度解析34-GPU安全架构深度解析

现代GPU不仅是图形处理器,更是高性能计算平台,安全架构设计至关重要。内存加密- 保护数据在传输和存储时的安全安全启动- 确保固件和软件的完整性隔离机制- 防止不同应用间的数据泄露密钥管理- 安全存储和处理加密密钥。

2301_79143213的博客 101

Java实现LeetCode 111. Minimum Depth of Binary Tree

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { publ...

南 墙 1万+

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

[LeetCode 111] Minimum Depth of Binary Tree

题目链接: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

瓦尔登湖 1394

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

LeetCode题目笔记(一) -- Minimum Depth Of Binary Tree

写博客,并且持续维护博客,是一件耗时费力的差事。但是,但凡耗时费力的差事,总有难得的收获。最近发现leetCode这个网站,很适合找码工工作的朋友,练习interview过程中的算法题。可以在这个网站提供的online console里面写代码(Java /C++), 然后如果通过他们的judge的话,我会通过SourceTree这个软件把代码上传到gitHub https://github.co

du5l5ljason的专栏 1129

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

[LeetCode]Minimum Depth of Binary Tree

解题思路: 宽度搜索。 边界条件:root 为NULL 前条件:queue,root->val  = 1(深度),push(root) 不变式:只要queue不空,取front,把它的左右子树push进queue(在这个逻辑之前,要判断 “结束条件”是否满足) 结束条件:如果front的左右子树均为NULL,找到了最浅的一片树叶,返回其val,就是树的深度  //

Leslie的专栏 500

LeetCode | 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. 分析 题目很简单,需要尽可能写得精炼。 有递归(DF

1931

[LeetCode] 111. Minimum Depth of Binary Tree

原题链接: https://leetcode.com/problems/minimum-depth-of-binary-tree/ 1. 题目介绍 Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root no...

Ber03的博客 177

leetcode之Minimum Depth of Binary Tree

采用递归思想,这次是求最小深度。 (1)C语言实现 /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     struct TreeNode *left;  *     struct TreeNode *right;  * };  */  int min(int x

代码草根的专栏 271

LeetCode 111. Minimum Depth of Binary Tree

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 ...

ZQYnn's blog 166

【LeetCode】 111. Minimum Depth of Binary Tree 二叉树的最小深度(Easy)(JAVA)

【LeetCode】 111. Minimum Depth of Binary Tree 二叉树的最小深度(Easy)(JAVA) 题目地址: https://leetcode.com/problems/minimum-depth-of-binary-tree/ 题目描述: Given a binary tree, find its minimum depth. The minimum depth...

qq_16927853的博客 277

leetcode 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 ...

leo_weile的博客 162

LeetCode - Easy - 111. Minimum Depth of Binary Tree

Topic Tree Breadth-first Search Depth-first Search Description https://leetcode.com/problems/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 do

KISS 298

从外包到正式员工:一年实现职场跃迁的实战策略与核心能力锻造

在软件开发与互联网行业中,职业发展路径与个人成长策略是技术人员普遍关注的核心议题。从技术执行到价值创造的跃迁,其底层逻辑在于理解企业用人模型与价值评估体系的差异。外包与正式岗位的本质区别,不仅在于合同形式,更在于企业对弹性化用工与长期人力资本投资的不同诉求。实现身份转换的关键,在于系统性地弥补信息差与权限差,将业务熟悉度与已验证的协作能力转化为差异化价值。通过深度融入、能力显性化、创造项目成果及有效沟通等阶段性策略,技术人员可以完成从任务执行者到问题所有者的思维转变。这一过程不仅适用于寻求转正的外包人员,也

weixin_30740295的博客 378
上一篇: LeetCode算法题-Balanced Binary Tree(Java实现)
下一篇: LeetCode算法题-Path Sum(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值