111. Minimum Depth of Binary Tree

手把手教你用LTspice仿真BUCK-BOOST电路(附波形分析) 本文详细介绍了如何使用LTspice进行BUCK-BOOST电路的仿真与波形分析,涵盖电路原理、CCM与DCM模式特性、效率优化及常见问题解决方案。通过实战案例,帮助工程师快速掌握升降压转换电路的设计与调试技巧,提升电力电子设计能力。 阅读详情
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.

解法一:BFS

class Solution {
public:
    int minDepth(TreeNode* root) {
        int count = 0;
        if(root == NULL)
            return count;

        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()){
            ++count;
            const int size = que.size();
            for(int i=0; i<size; ++i){
                TreeNode* tmp = que.front();
                que.pop();

                if(tmp->left == NULL && tmp->right == NULL)
                    goto final;

                if(tmp->left != NULL)
                    que.push(tmp->left);
                if(tmp->right != NULL)
                    que.push(tmp->right);
            }
        }
final:
        return count;
    }
};

注意双层循环,仅仅使用break是无法跳出来的,使用goto,或者直接return。

解法二:DFS

  if(root == NULL)
            return 0;
        int l = minDepth(root->left);
        int r = minDepth(root->right);
        return 1 + ((l != 0 && r != 0) ? std::min(l, r) : std::max(l, r));

注意当递归回去的时候,某个节点当前深度为0,我们要return较大的哪一个,否则此处节点的深度就成了“假0”!

【QNX+Android虚拟化方案】129 - USB眼图参数配置 阅读详情

相关推荐

基于Meteoinfo与TrajStat的后向轨迹聚类分析实战:从数据准备到可视化制图

本文详细介绍了基于Meteoinfo与TrajStat进行后向轨迹聚类分析的完整实战流程。从Java环境配置、Meteoinfo软件与TrajStat插件安装,到精准获取NOAA气象数据、设置参数进行批量轨迹计算,再到利用聚类分析提炼主要气流路径,并最终完成专业地图可视化与制图。文章旨在帮助环境与气象研究者快速掌握从数据准备到成果输出的全链路操作。

p4q5r6s7t的博客 815

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.

老夫编代码就是一把梭 596

磁传感器技术解析:从霍尔效应到车规级应用,纳芯微的本土第一之路

磁传感器是现代工业与汽车电子中的关键感知元件,其技术演进经历了从分立器件到高集成度SoC的跨越。霍尔效应与磁阻效应构成两大物理基础,其中硅基霍尔方案凭借高性价比与成熟供应链,在车规级应用中占据主流。高精度电流检测、角度与位置感知、磁开关等场景,对传感器的温漂抑制、共模瞬态抗扰与批量一致性提出严苛要求。车规级可靠性体系与系统级集成能力,成为衡量供应商的核心标尺。随着新能源主驱、光伏逆变、工业伺服等应用爆发,具备完整信号链与隔离技术积累的厂商正逐步构建护城河。本文以纳芯微为样本,剖析其从隔离技术延伸至磁传感器平

weixin_34387468的博客 380

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

金融学习之十三——数据去极值和标准化处理

拿到数据后,数据中可能会存在一些超大或极小的值,这些值与其他的值离得较远,显得格格不入,我们称其为离群点,有时也称为异常点。对于这些值,它的存在会导致影响最终的分析结果,带偏我们的分析。举个简单的例子,10个人的收入分别为2000,2500,2300,2425,2512,2375,2700,2265,2345,10000000,只算前9个,平均值就是2380,但加上最后一个,平均值就是1002144.2,就可能严重带偏最后分析的结果。因此,对于这样的数据,我们需要将其去除或修改。 (一)数据去极值 数据去极

ryo007gnnu的博客 7181

SAP成本核算的核心逻辑

SAP成本核算采用"计划-归集-分析"闭环管理,以CO模块为核心,集成PP、MM等模块。核算前需配置标准成本控制范围、成本中心等主数据。标准成本通过BOM和工艺路线计算(CK11N),采购和生产过程记录实际成本差异。制造费用通过成本中心归集,作业成本按实际耗用量分配。完工产品按标准成本入库,月末通过KO88结算工单差异,物料分类账(CKMLCP)还原实际成本。整个流程实现FI与CO数据同步,确保账务一致。关键事务码包括CK11N(成本估算)、MIGO(物料移动)、CO11N(报工)等。

金牌架构师 554

[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

【GlobalMapper精品教程】070:专题地图制作完整操作教程

与其它GIS软件一样,Globalmapper也可以制作出漂亮的地图,本文讲解专题地图制作完整操作流程。

智慧空间实验室 3772

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

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

emmm_Yeah的博客 292

【WRF-Urban】Registry.EM_COMMON文件概述及urban有关变量

Registry.EM_COMMON文件概述及urban有关变量

WW、forever的博客 1602

【点云概述】什么是点云、来源、种类、特点、处理?

【点云概述】什么是点云、来源、种类、特点、处理?点云(point cloud)是空间中点的数据集,可以表示三维形状或对象,通常由三维扫描仪获取。点云中每个点的位置都由一组笛卡尔坐标 ( X , Y , Z ) (X, Y, Z) (X,Y,Z)描述,有些可能含有色彩信息 ( R , G , B ) (R, G, B) (R,G,B)或物体反射面强度(Intensity)信。

智慧空间实验室 9852

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

基于生存结局(生存分析/COX回归)的中介效应分析

① 建立观察变量OVB和中介变量MVB的回归模型(注意:这里根据mediation包的介绍,需要构建的是probit模型,而不是logist回归模型,网上有很多的代码用的logistic回归,结果自己跑的时候发现报错,我在这里陷了很久;为了方便演示,我们生成了一个协变量(Age)、一个连续型观察变量(liaOVC)、一个二分类观察变量(OVB)、一个连续型中介变量(MVC)、一个二分类中介变量(MVB)以及最后的结局变量(生存时间[time],生存结局[stats])。

m0_61863309的博客 1万+

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

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

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

【LeetCode】111. Minimum Depth of Binary Tree

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

weixin_42344158的博客 257

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

111. Minimum Depth of Binary Tree [easy] (Python)

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

Coder_Orz的博客 3900

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

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. 即求根结点到其叶节点的最短距离。 简单地用BFS就可以解决问

Lau_r_k的博客 361

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.分析求二叉树的最小深度:根节点到最近叶子节点的路径长度。同样采用递归的思想: 当根

指尖飞舞 2325

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

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

小榕流光的专栏 1166

Leetcode【111】Minimum Depth of Binary Tree(Python版)

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(sel...

ssjdoudou的博客 7056

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.

leo1949asd的专栏 684

【Leetcode】111. Minimum Depth of Binary Tree 解题报告

求树的最小深度,深度为根节点到叶子节点的长度 方法1 递归 对于某个非None节点我们返回其左右子树最小的深度,但是要注意返回的值是否为0,如果为0,其最小深度就是另外一个子树的深度 class Solution: def minDepth(self, root): """ :type root: TreeNode :rtype: int ...

很吵请安静 394
上一篇: 208. Implement Trie (Prefix Tree)--Trie树
下一篇: 55. Jump Game(贪心)
FreeeLinux
博客等级 码龄11年 421粉丝 356原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址