Minimum Depth of Binary Tree

普通二叉树和右倾斜二叉树--LeetCode 111题《Minimum Depth of Binary Tree》 本文将以解释计算二叉树的最小深度的思路为例,致力于用简洁易懂的语言详细描述普通二叉树和右倾斜二叉树在计算最小深度时的区别。通过跟随作者了解右倾斜二叉树的概念以及其最小深度计算过程,读者也将对左倾斜二叉树有更深入的了解。这将为解决LeetCode 111题《Minimum Depth of Binary Tree》提供有力支持。最终,本文将提供LeetCode 111的解题代码。 阅读详情

方法一,递归。时间复杂度O(n),空间复杂度O(logN),分几种情况讨论:

(1) 空节点。 直接返回 0;

(2) 左右节点都为空(当前节点不为空), 则当前是叶子节点,返回1。

(3) 左节点(或者右节点)为空, 则该节点不为叶子节点,直接返回右节点(左节点)的最小高度+1.

(4) 左右都不为空,返回左右子树中的最小高度+1。

class Solution {
public:
    int minDepth(TreeNode *root) {
        return minDepth(root, false);
    }
    
    int minDepth(TreeNode *root, bool hasSibling)
    {
        if(root == NULL) 
            return hasSibling? INT_MAX:0;
            
        return std::min(minDepth(root->left, root->right), 
            minDepth(root->right, root->left)) + 1;
    }
};

方法二,使用队列,逐层遍历并记录层数(深度),当某一层发现有一个叶子节点时,则停止遍历。

时间复杂度O(n),空间复杂度O(n)。

class Solution {
public:
    int minDepth(TreeNode *root) {
        if(!root) return 0;
        queue<TreeNode*> queue;
        queue.push(root);
        queue.push(NULL);
        
        int depth = 1;
        while(!queue.empty()) {
            TreeNode *cur = queue.front();
            queue.pop();
            if(cur) {
                if(cur->left) 
                    queue.push(cur->left);
                if(cur->right) 
                    queue.push(cur->right);
                
                if(cur->left == NULL && cur->right == NULL)
                    break;
            }else
            {
                if(!queue.empty())
                {
                    queue.push(NULL);
                    depth++;
                }
            }
        }
        return depth;
    }
};


方法三,使用栈,DFS遍历。时间复杂度O(n),空间复杂度O(logN)。在每个node进栈的时候,同时需要记录它所在的深度,因此stack中的格式为<node, depth>

class Solution {
public:
    int minDepth(TreeNode *root) {
        
        if(root == NULL) return 0;
        
        stack<pair<TreeNode*,int> > s;
        int mindepth = INT_MAX;
        s.push(make_pair(root,1));
        
        while(!s.empty())
        {
            TreeNode *cur = s.top().first;
            int depth = s.top().second;
            s.pop();
            
            //this may not be the leaf with minimum depth
            //so here we cannot return
            if(cur->left == NULL && cur->right == NULL)
                mindepth = min(mindepth, depth);
            
            if(cur->left != NULL && mindepth > depth)
                s.push(make_pair(cur->left, depth+1));
            
            if(cur->right!= NULL && mindepth > depth)
                s.push(make_pair(cur->right, depth+1));
                
        }
        return mindepth;
    }
};




保姆级教程:2026版Windows电脑换新,微信QQ聊天记录无损搬家(附路径修改避坑指南) 本文提供2026版Windows电脑换新时微信QQ聊天记录无损迁移的保姆级教程,涵盖最新版微信/QQ的存储路径修改和避坑指南。通过详细步骤和实战技巧,确保数据迁移过程中不丢失任何珍贵对话记录和文件,特别适合需要保留完整聊天记录的用户。 阅读详情

相关推荐

馈电网络设计:通过Smith圆图工具完成微带线到同轴探针的阻抗匹配

Smith圆图通过图形化阻抗变换路径,显著简化微带线到同轴探针的匹配设计。设计需结合理论计算(微带线阻抗公式、探针等效模型)、圆图操作(串联/并联元件移动规则)及仿真验证,最终实现宽带低反射匹配。

百态·数智思维 | 聚焦大数据、量化与未来AI 1114

【LeetCode】111. Minimum Depth of Binary Tree

两种解法: (1)深度优先遍历,与maximum depth of binary tree类似,时间复杂度,递归函数栈结构空间复杂度,但需要考虑两种情况: i. 节点返回时必须为叶子节点,返回深度应该为1。 ii. 为了满足i.实现时要返回非空子树的最小深度。 (2)广度优先遍历,优势在于,深度优先遍历会遍历全部子树,这在树非常不平衡时效率比较低。可以采用广度优先遍历来克服...

weixin_42344158的博客 257

python blp模型 估计_随机系数Logit模型及Stata实现

欢迎投稿(荐稿)计量经济圈,计量相关都行邮箱:econometrics666@sina.cn作者:北京交通大学经济管理学院博士生,王琦珀。欢迎你加入计量经济圈社群,一起探讨前沿计量理论和实证方法。一、随机系数Logit模型1.背景实证产业组织(Empirical Industrial Organization,EIO)是目前产业组织理论的前沿,其中又以Ariel Pakes为带头人,其近期工作论文...

weixin_42298927的博客 2650

LeetCode | 0111. Minimum Depth of Binary Tree二叉树的最小深度【Easy】【Python】【二叉树】

LeetCode 0111. Minimum Depth of Binary Tree二叉树的最小深度【Easy】【Python】【二叉树】

Wonz 572

终端运行脚本报: 因为在此系统上禁止运行脚本。有关详细信息,请参阅 https:/go.microsoft.com/fw link/?LinkID=135170 中的 about_Execution_

PowerShell 执行策略是一种安全机制,用于控制哪些脚本可以在系统上运行。默认情况下,Windows 系统会设置较为严格的执行策略,以防止恶意脚本的执行。执行策略有以下几种常见级别:Restricted(限制):不允许运行任何脚本。AllSigned(全部签名):仅允许运行经过数字签名的脚本。RemoteSigned(远程签名):允许运行本地脚本,但远程下载的脚本需要数字签名。Unrestricted(无限制):允许运行所有脚本,但会警告未签名的脚本。

欢迎来到我的技术博客!这里是一个专注于软件开发的地方,我将分享关于 Java、Python、C++ 和易语言等多种编程语言的教程、技巧、最佳实践以及开发经验。 5117

企业微信微盘API权限避坑指南:为什么你的Python脚本无法获取文件列表?

本文深入解析了企业微信微盘API的权限模型,解释了为何即使使用超级管理员账号,Python脚本也可能因权限不足而无法获取文件列表。核心在于微盘API基于“应用身份”而非“用户身份”进行校验,应用只能访问自身创建的空间。文章提供了构建文件上传代理、利用事件回调等合规的替代方案,帮助企业实现高效数据同步。

weixin_29322553的博客 555

LeetCode之111. 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 childre...

iNiBuBian的博客 429

大疆OcuSync系统背后的黑科技:跳频扩频技术如何让你的无人机飞得更稳

本文深入解析了大疆OcuSync系统如何运用跳频扩频技术等先进无线通信方案,显著提升无人机在复杂环境下的飞行稳定性。系统通过跳频扩频与直接序列扩频技术协同工作,结合双频智能切换与多天线MIMO,有效对抗信号干扰与多径效应,确保控制指令与高清图传的可靠、低延迟传输,为用户带来更安心、更流畅的飞行体验。

ol7890123的博客 640

111.二叉树的最小深度(Minimum Depth of Binary Tree)

题目描述给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。说明: 叶子节点是指没有子节点的节点。示例:给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7返回它的最小深度  2.解题思路...

写后端的小学生 664

Python 爬虫实战:赛事分析平台构建与比赛数据抓取

在体育赛事日益丰富的今天,对比赛数据的收集与分析对于运动员、教练团队以及体育爱好者都具有重要意义。通过构建一个赛事分析平台,我们可以系统地抓取、整理和展示各类比赛数据,为用户提供全面的赛事洞察。本文将深入讲解如何利用 Python 爬虫技术实现这一平台的构建,涵盖从目标网站分析到数据可视化展示的全过程。

u014481728的博客 3189

常用元器件使用方法13:物理层接口芯片DP83848的使用方法

介绍: DP83848是以太网物理层接口芯片,具有多种型号,从便于焊接角度考虑LQFP-48封装较为合适,采用LQFP-48封装的芯片,有2种型号,分别为DP83848I和DP83848C,如下图所示。 其主要区别是使用温度不同,如下图所示。 这2种芯片芯片网上均有销售,按理说DP83848C价格应该更加便宜,实际不然,DP83848I的价格低于DP83848C,考虑或与芯片的出货量...

snmplink的博客 1万+

leetcode笔记 111. Minimum Depth of Binary Tree & 112. Path Sum

leetcode刷题16天 111. 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 lea...

qq_29868413的博客 148

[VCS]VCS checkpoint简介以及其在SoC验证加速中的作用

VCS checkpoint是Synopsys VCS提供的快照/恢复机制,可显著加速SoC验证。其核心是在仿真关键节点(如完成初始化后)保存系统状态,后续测试可直接从该点恢复,避免重复执行冗长的初始化阶段(如boot、DDR训练等)。该技术特别适用于多测试用例共享同一初始状态的场景,通过分离初始化与功能验证流程,可提升回归效率3-5倍。需注意处理DPI-C状态同步、版本管理及存储优化等问题,结合UVM和自动化脚本可实现更高效的验证流程。典型应用可节省数百万cycle的重复仿真时间。

元直的博客 795

LeetCode 104. Maximum Depth of Binary Tree和111. Minimum Depth of Binary Tree 递归

104. Maximum Depth of Binary Tree Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

老夫编代码就是一把梭 595

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

33. Minimum Depth of Binary Tree && Balanced Binary Tree && Maximum Depth of Binary Tree

Minimum Depth of Binary Tree OJ: https://oj.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 short...

weixin_30408309的博客 131

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

LeetCode: 111. Minimum Depth of Binary Tree

LeetCode: 111. 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...

杨领well的专栏 688

深度学习工具包 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

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

du5l5ljason的专栏 1129

LeetCode: Minimum Depth of Binary Tree

LeetCode: Minimum Depth of Binary Tree LeetCode: Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along t...

weixin_34111819的博客 120

[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

LeetCode Minimum Depth of Binary Tree

求一棵二叉树的最小高度,即从根节点到最近叶子节点的路径经过的节点数。

DRFish 1267

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

西施豆腐渣 2278

Leetcode 111 Minimum Depth of Binary Tree(水)

题目连接:Leetcode 111 Minimum Depth of Binary Tree解题思路:递归,每次返回子树中层数低的一个加一。/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * ...

不慌不忙、不急不躁 208

【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. 题意:求最小路径。 方法一:递归 class Soluti

lplp90908的博客 274

9.14 DFS 简单 111 Minimum Depth of Binary Tree 112 Path Sum

111 DFS 不太熟练的用法 好法多磨 112 DFS 比较典型的例子

emmm_Yeah的博客 292
上一篇: Longest Substring Without Repeating Characters
下一篇: Path Sum
zhaobaoxue
博客等级 码龄19年 3粉丝 102原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值