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

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

104. 二叉树的最大深度

一、题目描述

在这里插入图片描述

二、理解

对照二叉树的递归定义:

  • 如果树为空,则它是一个空树。
  • 如果树不为空,它由一个根节点和两个子树组成,分别是左子树和右子树,且左子树和右子树本身也是二叉树。
    采用递归形式解决问题:
  • 首先判断 root 是否 null,若为 null,则该树的的深度为0。
  • 若 root 不为 null,则该树的最大深度为,max (左子树的最大深度, 右子树最大深度) + 1。
    请添加图片描述

三、代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return Math.max(leftDepth, rightDepth) + 1;
    }
}
LeetCode——104,二叉树的最大深度 /** * \* Created: liuhuichao * \* Date: 2019/8/22 * \* Time: 35:25 AM * \* Description: 二叉树的最大深度 * \ * 给定一个二叉树,找出其最大深度。 * <p> * 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 * <p> * 说明: 叶子节... 阅读详情

相关推荐

汽车LED驱动芯片TPS92682-Q1 SPI接口配置与调试实战指南

SPI(串行外设接口)作为一种高速、全双工的同步串行通信总线,广泛应用于微控制器与外围设备之间的数据交换。其工作原理基于主从架构,通过时钟、数据线和片选信号实现设备间的精准时序控制。在汽车电子和工业控制领域,SPI因其简单高效、易于扩展的特性,成为配置复杂电源管理芯片、传感器和存储器的关键技术。通过SPI接口,工程师能够动态调整设备参数、实时读取状态信息,并实现复杂的故障诊断与保护策略,极大地提升了系统的灵活性与可靠性。本文以汽车级双通道LED恒流驱动器TPS92682-Q1为例,深入解析如何通过SPI接口

weixin_29185493的博客 288

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

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

yyh520025的博客 1330

UVM(5)-TLM通信

TLM是一种基于事务 (transaction) 的通信方式,通常在高抽象级语言例如SystemC或者SV/UVM中作为模块之间的通讯方式。

2301_76431006的博客 2106

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

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

qq_40263592的博客 2211

飞书多维表格+影刀RPA:我如何用3个指令搞定每周的销售数据自动汇总(附完整配置截图)

本文详细介绍了如何利用飞书多维表格和影刀RPA实现销售数据的自动化汇总,通过三个核心指令(建立链接、列出记录、更新记录)简化繁琐的手工操作。文章包含完整的配置截图和实战指南,帮助用户快速部署自动化流程,提升工作效率。

weixin_29273849的博客 284

基于RYU+Mininet的SDN校园网络实战:从零搭建虚拟化实验环境

本文详细介绍了如何利用RYU控制器和Mininet搭建SDN校园网络实验环境,从Ubuntu虚拟机准备到网络拓扑设计,再到关键网络功能实现。通过实战案例展示SDN在校园网络中的应用优势,包括简化配置、提升效率等,为网络工程师和学生提供了一套完整的虚拟化实验方案。

weixin_30872499的博客 455

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

龙头复盘神器/复盘于导出工具最新版5.6

龙头复盘神器,复盘于导出工具

初入python踩过的坑 8232

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

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

Jiewang的博客 351

【TC3xx芯片】TC3xx芯片UCB详解

TC3xx芯片UCB详解

qq_36056498的博客 1万+

YOLOv11 改进 - 特征融合 | 替换 C3k2 涨点:GELAN 融合 CSP+ELAN 提精度

本文介绍了可编程梯度信息(PGI)和广义高效层聚合网络(GELAN)与 YOLOv11 的结合,以解决深度网络数据传输时的信息丢失问题。PGI 能为目标任务提供完整输入信息,计算目标函数以更新网络权重。GELAN 作为轻量级网络架构,由 SPPELAN、ELAN1、RepNCSPELAN4 等模块组成。我们将 GELAN 代码集成进 YOLOv11, 实验脚本显示,结合 GELAN 的 YOLOv11 在 MS COCO 数据集目标检测任务中或有良好表现。

魔改工程师的博客 1242

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

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

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

深入大模型-13-大模型Skills应用之标准目录结构和开发一个Skill的步骤

首先对比Prompt工程,上下文工程,Skills工程,MCP工具的概念与区别,然后介绍Skill的标准目录结构,同时描述了开发一个Skill的步骤和最佳实践。

qq_20466211的博客 748

LeetCode 104.二叉树的最大深度

目录LeetCode 104.二叉树的最大深度题目描述解题 LeetCode 104.二叉树的最大深度 题目描述 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 返回它的最大深度 3 。 解题      /** * Definition for a binary tree node. * struct TreeNode { * int va

s_Shune 2287

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

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

LeetCode 104.二叉树的最大深度(DFS、BFS)

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

晴空๓ 1948

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

《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

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

(力扣)LeetCode104. 二叉树的最大深度(C语言)

【代码】(力扣)LeetCode104. 二叉树的最大深度(C语言)。拆分递归的细节,从本质认识递归

墨染 677

LeetCode 104二叉树的最大深度

LeetCode 104二叉树的最大深度 题目 解析 写一个递归函数,返回最大深度 代码 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) {...

UN_uomo的博客 377

LeetCode 力扣 104. 二叉树的最大深度 maxDepth

大家觉得写还可以,可以点赞、收藏、关注一下吧! 也可以到我的个人博客参观一下,估计近几年都会一直更新!和我做个朋友吧!https://motongxue.cn 文章目录104. 二叉树的最大深度说明:示例:代码运行结果在这里插入图片描述 104. 二叉树的最大深度 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20

motongxue的博客 652

LeetCode 104 二叉树的最大深度

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

sdm12345的博客 231

Leetcode104 二叉树的最大深度 C++,Java,Python

Leetcode104 二叉树的最大深度 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/ 博主Github:https://github.com/GDUT-Rp/LeetCode 题目: 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说...

Rp的博客 288

LeetCode 104. 二叉树的最大深度

LeetCode 104. 二叉树的最大深度 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 由于面试中面试官基本上不会让你写递归版本的深度求解,所以使用层次 遍历求解树的最大深度 题解:层次遍历 使用队列,每次将每一层的树节点放进队列中,每次在放每一层的节点时需要将以前的节点全部取出来,保证队列里存放的是当前层的所有节点,每次操作一层的节点,所以需要记住我们操作了几次即可 。 public class max

小小鹿 151

LeetCode 104 二叉树的最大深度 Java

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

qq_29061435的博客 232

【力扣刷题记录——104. 二叉树的最大深度】

链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree/solutions/2361697/104-er-cha-shu-de-zui-da-shen-du-hou-xu-txzrx/

weixin_45441887的博客 1051

Leetcode104. 二叉树的最大深度

Leetcode104. 二叉树的最大深度 题目: 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7],         3         /  \ &nb...

会流泪de鱼的博客 289

LeetCode 104:二叉树的最大深度

LeetCode 104:二叉树的最大深度题目描述解题思路代码实现总结 题目描述 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 返回它的最大深度 3 。 解题思路 递归思路,依次求取左子树和右子树的...

香农三定律的博客 170
上一篇: 力扣反转链表系列【25. K 个一组翻转链表】——由易到难,一次刷通!!!
下一篇: 力扣 237. 删除链表中的节点【狸猫换太子】
JZihui
码龄6年 170粉丝 65原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值