[LeetCode]二叉树的最大深度

DAY16:二叉树(五)二叉树最大深度+最小深度 例如上图中的节点20,深度是2(到根节点距离是2),节点7的深度就是3,到根节点距离为3个节点。这是因为在 C++ 中,函数的参数是按值传递的,所以对参数的修改不会影响到函数调用之外的代码。注意,这道题中提到的最小深度,是根节点到最近的叶子节点的距离,也就是说,如下图所示的树,最小深度应该是3而不是1!或者在调方法参数的时候传入参数+1,这样就不改变变量本身的值,就不需要还原,效果是一样的。,而后序的遍历顺序是左右中,可以把叶子节点的信息返回给父节点,父节点直接在叶子节点高度信息+1即可。 阅读详情

///////////////////////////////////////////////////////////////////////////////////////////////////////

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

///////////////////////////////////////////////////////////////////////////////////////////////////////

树的遍历还是用递归比较好,虽然很长时间不碰代码,但还是硬着头皮写了。

思路很简单,每遍历一个结点,层数计数+1,直到叶子节点,把得到的层数与最大层数比较大小,最终返回最大层数。

果然,还是写的太笨了,放在这仅供参考。

class Solution 
{
	int mdepth = 0;
public:
	int isEnd(int d, TreeNode *r)
	{
		d++;
		TreeNode *left = r->left;
		TreeNode *right = r->right;
		if (left == NULL)
		{
			if (d > mdepth)
				mdepth = d;
		}
		else
			isEnd(d, left);
		if (right == NULL)
		{
			if (d > mdepth)
				mdepth = d;
		}
		else
			isEnd(d, right);
		return mdepth;
	}

	int maxDepth(TreeNode* root) 
	{
		int depth = 0;
		if (root == NULL)
			return mdepth;
		mdepth = isEnd(depth, root);
		return mdepth;
	}
};

顺便贴一个4ms的范例:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int max = 0;
        if (root != NULL) {
            max++;
            int max_left = maxDepth(root->left);
            int max_right = maxDepth(root->right);

            max += max_left>max_right ? max_left:max_right;
        }
        return max;
    }
};

差距可以说是很明显了。

【简单】力扣算法题解析LeetCode104:二叉树的最大深度 本文介绍了如何计算二叉树的最大深度。采用深度优先搜索(DFS)的递归方法,通过比较左右子树的最大深度并加1(当前节点)得到结果。该方法时间复杂度为O(n),空间复杂度为O(h),h为树高。代码简洁高效,适用于各种二叉树结构。附带Java实现和示例说明,帮助理解算法原理。 阅读详情

相关推荐

GAN管CGH40010F设计宽带Doherty功放:如何用ADS搞定输入匹配、合路网络与功分器?

本文详细介绍了基于CGH40010F GaN晶体管的宽带Doherty功放设计流程,重点讲解在ADS平台中实现输入匹配网络、合路网络与功分器的关键技术。通过寄生参数补偿、渐变微带线设计和复合补偿结构等方法,解决了宽带化设计中的核心挑战,最终实现1.7-2.6GHz频段内72%的峰值效率和52%的回退效率。

weixin_42614269的博客 473

二叉树的最大深度

二叉树的最大深度 求解二叉树的最大深度的三种方式 方式一:使用广度优先遍历 广度优先遍历 又叫层次遍历,从上往下对每一层依次访问,在每一层中,从左往右(也可以从右往左)访问结点,访问完一层就进入下一层,直到没有结点可以访问为止。二叉树的广度优先遍历的非递归的通用做法是采用队列。 思路加代码 方式二:使用深度优先遍历 广度优先遍历 思路加代码 方式三:使用递归的解法 广度优先遍历 思路加代码 ...

qq_46589658的博客 1715

百度慧眼人口位置数据:从原理到实战的GIS处理全流程

本文详细解析百度慧眼人口位置数据的处理全流程,从基本原理到实战应用。通过空间网格划分、终端数量统计等技术手段,百度慧眼数据能准确反映人群分布特征。文章涵盖坐标系转换、核密度分析、热力图制作等GIS处理技巧,并分享商业选址、城市规划等典型业务场景的解决方案,帮助读者高效利用这一数据资源。

weixin_30872157的博客 534

求二叉树的最大深度的三种方法

求二叉树深度的三种方法:递归、层次遍历、深度遍历 递归: class Solution: def TreeDepth(self, p): # write code here # 终止条件: if not p: return 0 return max(self.TreeDepth(p.left), s...

qq_36013249的博客 1718

PyTorch ModelNet点云数据集加载实战:从下载到Dataset类完整实现

在三维视觉与点云处理领域,数据集是算法研发的基石。ModelNet作为三维物体分类的基准数据集,其地位类似于图像领域的MNIST,是入门和评估模型性能的通用标准。理解其数据格式与加载原理,是进行点云分类、分割等任务的关键前置步骤。通过PyTorch的Dataset类,开发者可以构建高效的数据管道,将原始点云文件转换为神经网络可直接处理的张量格式,这一过程涉及数据采样、归一化、特征组装等核心操作,直接影响模型的训练效率和最终性能。本文聚焦于ModelNet10/40数据集,详细解析其目录结构,并提供一套稳健的

weixin_29032337的博客 283

避坑指南:为什么你的conda环境装不上Mamba?从CUDA到ABI的深度排查

本文深入解析conda环境中安装Mamba架构时常见的CUDA版本冲突、ABI不匹配等问题,提供从基础检查到深度排查的系统化解决方案。针对`causal-conv1d`和`mamba-ssm`安装失败场景,详细讲解PyTorch版本绑定、编译器工具链兼容性等关键技术要点,并给出预编译wheel选择、动态链接库配置等实用修复方案。

weixin_33738555的博客 346

求二叉树的最大深度两种方法实现及对比

给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 **示例:**给定二叉树 [3,9,20,null,null,15,7], 思考 第一种方法,层次遍历 第二种方法,前序遍历递归法 层次遍历 layerNodes:代表当前层节点数 temp:下一层节点数 max:代表最大深度 package 力扣; import java.util.ArrayList; import java.util.LinkedList; impor

小菜鸡 630

30 中望CAD二次开发(ZRX C++)-windows下的qt开发

本文介绍了中望CAD在windows下,如何使用qt开发插件界面,给出了具体的编码步骤,并生成了模态对话框和非模态对话框,其中非模态对话框可以调用CAD命令,实现交互操作。

cilvsuanna的博客 191

力扣的二叉树的最大深度解法(Python3)

力扣的二叉树的最大深度解法 题目描述: 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 返回它的最大深度 3 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/...

chutu2018的博客 291

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

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

元直的博客 781

用Python爬取大连商品交易所期货实时行情:从入门到实战

python复制编辑# utils.py"豆粕": "M0","铁矿石": "I0","聚乙烯": "L0","玉米": "C0","聚丙烯": "PP0","棕榈油": "P0"本项目展示了:✅ 如何从新浪财经 API获取主力合约实时数据✅ 使用Python异步爬虫技术) 提升效率✅ 利用pandas和matplotlib进行结构化分析与可视化✅ 具备良好的扩展性,可对接金融、农业、能源等数据需求场景✅ 可作为期货量化策略数据源✅ 可嵌入自动化报告系统。

2201_76125261的博客 1248

瑞_力扣LeetCode_104. 二叉树的最大深度

力扣LeetCode_104. 二叉树的最大深度

阿瑞——从事Java后端,喜欢研读源码、自研框架、分享经验 1229

2026工控高薪:C#上位机面试15题(含答案)

基础岗(10-15K):考察串口/Modbus/PLC通信基础;资深岗(20-30K):考察工业级优化(抗干扰/断线重连)、物联网(MQTT)、跨协议整合;架构岗(30K+):考察上位机架构设计、边缘计算、项目落地避坑。我整理了2026年近20场高薪岗位(月薪20K+)的面试高频题,筛选出15道核心题,每题标注“考察点+实战答案”——答案拒绝纯理论,全部结合车间现场、PLC通信、物联网落地等真实场景,帮你避开“背答案但不落地”的面试坑。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1290

104. 二叉树的最大深度【 力扣(LeetCode) 】

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。给定一个二叉树 root ,返回其最大深度。【h 是树高,递归最高深度就是树高】

yyh520025的博客 1335

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

LeetCode:二叉树的最大深度(Python版本)

LeetCode刷题日记二叉树的最大深度Python代码 二叉树的最大深度 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 返回它的最大深度 3 。 Python代码 # Definition for a binary tree node. #...

Cassiel_Coder的博客. 475

深度学习工具包 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】104 二叉树的最大深度

题目描述(难度易) 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 返回它的最大深度 3 。 链接 https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/ 思路 1、通过递归...

Jiewang的博客 351

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

二叉树的最大深度,力扣

是指从根节点到最远叶子节点的最长路径上的节点数。

m0_70437378的博客 1238

《LeetCode力扣练习》第104题 二叉树的最大深度 Java

《LeetCode力扣练习》第104题 二叉树的最大深度 Java 一、资源 题目: 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 返回它的最大深度 3 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximum-depth-of-bina

XRT_knives的博客 225

Leetcode 104. 二叉树的最大深度

Leetcode 104. 二叉树的最大深度1、问题分析2、问题解决3、总结 1、问题分析 题目链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/   本质上就是一个二叉树的遍历问题。代码我已经进行了详细的注释,理解应该没有问题,读者可以作为参考,如果看不懂(可以多看几遍),欢迎留言哦!我看到会解答一下。 2、问题解决   笔者以C++方式解决。 #include "iostream" using namespace std;

珍惜 8890

力扣练习第二十七天——二叉树的最大深度

力扣练习第二十六天——二叉树的最大深度 题目大致如下: 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7] 返回它的最大深度 3 。 链接来源于LeetCode:https://leetcode-cn.com/problems/maximum-dept...

weixin_43873644的博客 251

LeetCode第104题_二叉树的最大深度

给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。叶子节点是指没有子节点的节点。

qq_40263592的博客 2217

《LeetCode力扣练习》代码随想录——二叉树(二叉树的最大深度---Java)

《LeetCode力扣练习》代码随想录——二叉树(二叉树的最大深度---Java)

XRT_knives的博客 498

104. 二叉树的最大深度 - 力扣(LeetCode)

是指从根节点到最远叶子节点的最长路径上的节点数。​ 给定一个二叉树。

q1111111da的博客 354

LeetCode 104. 二叉树的最大深度

104. 二叉树的最大深度 题目描述: 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 官方题解链接: https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/er-cha-shu-de-zui-da-shen-du-by-l

kk1314sunny的博客 241

LeetCode二叉树最大深度

LeetCode二叉树最大深度 题目如下 3 / \ 9 20 / \ 15 7 代码如下 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x),

weixin_45998260的博客 169
上一篇: [LeetCode]环形链表
下一篇: [leetcode]验证二叉搜索树
web10t
博客等级 码龄10年 3粉丝 7原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值