leetcode 1302. Deepest Leaves Sum(叶子节点的和)

求二叉树最浅叶子结点们的和 #include <stdio.h> #include <string.h> #include <assert.h> #include <malloc.h> #define maxlen 30 typedef struct Node { struct Node * leftChild; struct Node * rightCh... 阅读详情

在这里插入图片描述
给一棵二叉树,求叶子节点的和。

思路:
方法一:
直接BFS,记录下每层的和,最后返回的就是最后一层的和。

    public int deepestLeavesSum(TreeNode root) {
        int res = 0;
        
        Queue<TreeNode> queue = new LinkedList<>();
        
        queue.add(root);
        
        while(queue.size() > 0) {
            int size = queue.size();
            res = 0;
            for(int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                res += cur.val;
                if(cur.left != null) queue.add(cur.left);
                if(cur.right != null) queue.add(cur.right);
            }
        }
        return res;
    }

方法二:
叶子节点肯定是left和right都为null的层,
为了记录是同一层,用一个leafLevel记录当前层数,是同一层就相加,
新的一层就重新让sum = root.val。

class Solution {
    int res = 0;
    int leafLevel = 0;
    
    public int deepestLeavesSum(TreeNode root) {
        helper(root, 0);
        return res;
    }
    
    void helper(TreeNode root, int level) {
        if(root == null) return;
        
        if(root.left == null && root.right == null && level == leafLevel) {
            res += root.val;
        }
        if(root.left == null && root.right == null && level > leafLevel) {
            leafLevel = level;
            res = root.val;
        }
        helper(root.left, level + 1);
        helper(root.right, level + 1);
    }
}
2020秋招提前批 柠檬微趣笔试题目 2020秋招提前批 柠檬微趣笔试题目声明第一题类型:二叉树、遍历与筛选第二题类型:数位第三题类型:数组、子集第四题类型:编码、转换 声明 2020秋招提前批柠檬微趣的笔试题,最终解释权归柠檬微趣所有。 笔试平台是牛客网 第一题 类型:二叉树、遍历与筛选 题目: 二叉树最浅叶节点和 举例: 对于这个二叉树,叶节点有2、8、9、13、21五个,其中最浅的是深度为3的三个叶节点:2、13、21,因此最浅叶节点和就是2+13+21=36 第二题 类型:数位 题目: 寻找一个数字数位重组后的略大数 举例 阅读详情

相关推荐

寻找二叉树最远的叶子结点(实例讲解)

下面小编就为大家分享一篇寻找二叉树最远的叶子结点的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

求二叉树最浅叶节点的和java_寻找二叉树最远的叶子结点(实例讲解)

面试的时候碰到一个题:如何找到一个二叉树最远的叶子结点,以及这个叶子结点到根节点的距离?第一反应肯定是递归如何能找到最远的叶子结点,同时也能记下这个叶子节点到根节点的距离呢?采用一个list保持从根节点到叶子节点的路径就可以了,这个list的长度-1就是叶子结点到根节点的距离,list的最后一个结点就是到叶子结点二叉树我就不用设计了,具体代码参见我的/*** 寻找最远的叶子节点*/public v...

weixin_42139357的博客 1022

Android PackageManagerService 总结(一)应用市场下载安装apk流程

前言: 本篇文章是对系统包安装流程的总结,基于Android12 上 com.android.packageinstaller 源码的分析,第三方应用商城(华为商城,小米商城,应用宝,豌豆荚,酷安等)下载安装应 用,在普通安装和静默安装app两种方式下,对代码流程的梳理和讲解。 触发安装: 当你在商城界面中点击安装按钮,应用会自动下载,下载完成后就会调起系统安装应用的界面,此种触发方式一般是通过Intent 隐式调用的,我们先阅读如下代码: ......

u012514113的专栏 1万+

129. 求根到叶子节点数字之和(JS实现)

1 题目 给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。 例如,从根到叶子节点路径 1->2->3 代表数字 123。 计算从根到叶子节点生成的所有数字之和。 说明: 叶子节点是指没有子节点的节点。 示例 1: 输入: [1,2,3] 1 / 2 3 输出: 25 解释: 从根到叶子节点路径 1->2 代表数字 12. 从根到叶子节点路径 1->3 代表数字 13. 因此,数字总和 = 12 + 13 = 25. 示例 2:

zjw_python的博客 721

三甲医院网络架构与安全建设实战

华为OceanStor] [华为OceanStor][PACS存储双活] [HIS数据库同步]患者隐私 数据脱敏 天清Web防火墙动态脱敏策略。主数据中心 --[OTV专线]-- 备数据中心。实现医疗业务网/卫生专网/互联网三网隔离。核心业务配置(华为CE6865)自动备份配置(每天02:00)安全事件响应(30分钟SLA)漏洞扫描(每周日00:00)实现医疗物联网统一接入管控。五、等保2.0合规关键配置。堡垒机登录(双因素认证)四、医疗物联网安全方案。

有小小的远大抱负 1922

旋转变压器软件解码simulink仿真

旋转变压器软件解码simulink仿真、电机转速位置测量

qq_31446727的博客 2596

LeetCode 111[Python]. 二叉树的最小深度 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

LeetCode 111. 二叉树的最小深度 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。 Code def minDepth(self, root: TreeNode) -> int: if root == None: return 0 q=[root]#将起点加入 res=1 while q != None: n=len(q)#n也会更新

vvv__vvv的博客 655

MacX DVD Ripper Pro for Mac(DVD解码器) 6.2.120190416免激活版

只需要5分钟即可转档一张DVD光碟!并允许我们在编码之前预览、编辑、裁剪、修剪或扩展视频。第一款也是唯一一款能够支持DVD到MP4,H.264,MOV,FLV,MPEG4等所有格式DVD(新DVD,99-标题DVD,损坏和无法播放的DVD)和翻录DVD / ISO映像的工具,AVI,QT,MP3等。借助350多种预设配置文件MacX DVD Ripper Pro for Mac(DVD解码器) 6...

llhf688的博客 899

(Java)leetcode-1302 Deepest Leaves Sum(层数最深叶子节点的和)

常规的深度相关的题。

不思量 298

FortiClient EMS实战:从安装到配置的全流程优化指南

本文详细解析了FortiClient EMS 7.0版本的部署与优化全流程,帮助企业构建零信任终端安全体系。从环境规划、高效安装、终端纳管到高级运维,提供实战指南和优化技巧,特别适用于Windows Server环境,助力企业提升终端安全管理效率。

weixin_29325007的博客 559

Matcap与菲涅尔

菲尼尔效果(简化版公式):fresnel = base + scale*((1-v*n)^power)透明队列为后前渲染,不关闭深度写入则会覆盖之前的像素,导致混合不了。y的值为0~1,根据x3返回对应y值。两色混合做个demo看看!混合为什么要关闭深度写入?

weixin_62773441的博客 386

Leetcode 1302.层数最深叶子节点的和(Deepest Leaves Sum)

Leetcode 1302.层数最深叶子节点的和 1 题目描述(Leetcode题目链接)   给你一棵二叉树,请你返回层数最深的叶子节点的和。 输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8] 输出:15 提示: 树中节点数目在 1 到 10410^4104 之间。 每个节点的值在 1 到 100100100 之间。 2 题解   ...

qq_39378221的博客 327

汽车ECU诊断入门:手把手教你用UDS协议(ISO14229)读取和清除故障码

本文详细介绍了如何使用UDS协议(ISO14229)进行汽车ECU诊断,包括故障码读取与清除的完整流程。从诊断环境搭建、UDS协议基础到实战案例分析,手把手教你掌握0x19诊断服务、安全访问机制等核心技能,适用于汽车电子工程师和诊断开发人员。

weixin_33701251的博客 471

leetcode 1302. Deepest Leaves Sum 层数最深叶子节点的和-耗时100

Problem:耗时100%,深度优先搜索,层数累加的,拿到每一层叶子结点的累加和,最后返回深度最深的累加和。

邹九的个人博客 66

Winform从入门到精通(1)——Label(史上最全)

本篇文章是对专栏《winform控件从入门到精通》的详细介绍

qq_34059233的博客 4万+

inori mmd 7z

楪祈的模型资源....................................................................................................................................................................................................................

Leetcode-1302. Deepest Leaves Sum 层数最深叶子节点的和 -python

题目 给你一棵二叉树,请你返回层数最深的叶子节点的和。 链接:https://leetcode.com/problems/deepest-leaves-sum/ Given a binary tree, return the sum of values of its deepest leaves. Example: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 思路及代码 DFS # Definition f

JamieLuo的博客 292

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

1302. Deepest Leaves Sum**

1302. Deepest Leaves Sum** https://leetcode.com/problems/deepest-leaves-sum/ 题目描述 Given a binary tree, return the sum of values of its deepest leaves. Example 1: Input: root = [1,2,3,4,5,null,6,7,nul...

珍妮的选择的博客 871

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

LeetCode 1302 Deepest Leaves Sum

1302 Deepest Leaves Sum https://leetcode.com/problems/deepest-leaves-sum/ Given the root of a binary tree, return the sum of values of its deepest leaves. Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Example 2: Input: ro

cyberickk blog 192

[leetcode] 1302. Deepest Leaves Sum

Description Given a binary tree, return the sum of values of its deepest leaves. Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Constraints: The number of nodes in the tree is between 1 and 10^4. The value of nodes is betw

Learning from the mistakes 230

Leetcode 1302. Deepest Leaves Sum(两种方法)

Leetcode 1302. Deepest Leaves Sum 题目链接: Deepest Leaves Sum 难度:Medium 题目大意: 求二叉树最深叶子结点的和,即最后一层所有叶子节点之和。 思路: 思路1 : 利用二叉树的层级遍历,计算出每一层节点的和,最后一层节点的和就是最深叶子节点的和。 思路2(递归): 参考高赞回答 ,递归,用level来标记当前的层数,详见代码。 代码 思路1代码 /** * Definition for a binary tree node. * publi

xue1236的博客 278

1302. Deepest Leaves Sum [Medium]

https://leetcode.com/problems/deepest-leaves-sum/ Given a binary tree, return the sum of values of its deepest leaves. Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Constraints: The number of nodes in the tree is b

Young's Blog 220

LeetCode - Medium - 1302. Deepest Leaves Sum

Topic Tree Depth-first Search Description https://leetcode.com/problems/deepest-leaves-sum/ Given the root of a binary tree, return the sum of values of its deepest leaves. Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 E

KISS 223

​力扣解法汇总1302-层数最深叶子节点的和

​力扣解法汇总1302-层数最深叶子节点的和

分享+记录 321

【leetcode】1302. Deepest Leaves Sum

题目描述: https://leetcode.com/problems/deepest-leaves-sum/ 题目大意: 输出最深层叶子节点的值之和 解题思路: 使用基于双端队列的层序遍历,输出最后一层所有节点值的和。 python双端队列操作: #实例化一个双端队列: q = deque() #Double Ended QUEue #常用操作: q.appendleft(1) #从最左端把元素添加进队列 q.append(2) #从最右端把元素添加进队列 q.po

qq_36294507的博客 261

leetcode 1302. Deepest Leaves Sum(python)

描述 Given the root of a binary tree, return the sum of values of its deepest leaves. Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Example 2: Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 19 Note: The

王大呀呀的博客 436

LeetCode|1302. Deepest Leaves Sum

一次AC ^ __________________________________ ^ 加油~出于想练习BFS,这题我用了广度优先的思路来做。这道题既可以用DFS也可以用BFS来解。

iLOVEJohnny的博客 426
上一篇: 并行bit count算法
下一篇: leetcode 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree(在BT的copy中找到对应的节点)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址