LeetCode刷题笔录Sum Root to Leaf Numbers

小龙虾 OpenClaw 安装全攻略:本地部署 AI 智能体一步到位 OpenClaw(昵称小龙虾)是一款 MIT 开源协议的本地优先 AI 智能体执行网关,支持多平台接入、本地部署,能实现自然语言驱动的设备自动化操作,区别于纯对话 AI,可直接操控系统执行实际任务,数据全程本地存储更安全。本文带来 2026 最新版 OpenClaw 安装教程,适配 Windows/macOS/Linux 全系统,新手也能一键搞定。 阅读详情

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.


还是不大习惯递归,总是本能地去用非递归的方法。不过这题还是递归比较简单好写。把到当前节点为止的sum作为参数进行传递。遇到leaf的话就把sum*10+node.val返回。sum*10就是这题的要点了。

这里有一个比较详尽的想法。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumNumbers(TreeNode root) {
        if(root == null)
            return 0;
        return sumNumbers(root, 0);
    }
    
    public int sumNumbers(TreeNode node, int sum){
        if(node == null)
            return 0;
        if(node.left == null && node.right == null)
            return sum * 10 + node.val;
        return sumNumbers(node.left, sum * 10 + node.val) + sumNumbers(node.right, sum * 10 + node.val);
    }
    
}


手把手教你用Simulink搭建DSOGI-PLL模型(附完整代码下载) 本文详细介绍了在Simulink中搭建高鲁棒性DSOGI-PLL模型的完整工程实践指南。针对传统锁相环在非理想电网下的不足,文章深入剖析了双二阶广义积分器锁相环(DSOGI-PLL)的核心原理与优势,并提供了从模块构建、系统组装到参数整定与测试验证的全流程手把手教程,附有完整代码下载,助力工程师应对谐波、电压跌落等复杂电网工况。 阅读详情

相关推荐

MagicDraw-用例图

MagicDraw-用例图

木头征的博客 3129

LeetCode刷题笔录 Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. Fo

likecool21的专栏 1万+

解决Windows 10安装语言包时遇到的0x800F0954错误

在安装Windows 10操作系统的语言包时,如果遇到错误代码0x800F0954的提示,这无疑会让许多用户感到困惑和无助。这个错误通常意味着在安装过程中遇到了一些阻碍,导致无法正常完成语言包的安装。本文将为大家详细解析这个错误代码0x800F0954,并提供一系列有效的解决方法,帮助大家顺利安装所需的语言包。

nntxthml的博客 3793

LeetCode刷题笔录 Two Sum

Two Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the

likecool21的专栏 1万+

Matlab处理气象数据(六)数据的面积加权

由于地理投影导致导致每个像元实际地面面积不同,越靠近北极实际面积越小,越靠近赤道实际面积越大,如果不进行面积加权就简单平均,会导致温度较实际温度偏低。 用以下公式计算地理投影每个像元的面积: double pi = 3.1415926; double R = 6371007.181; //units - m double area = (pi/180.0)*R*R*fabs(sin(dLat1/180.0*pi) - sin(dLat2/180.0*pi)) * fabs(dLon1 - dLo

设计の诗 1万+

数据产品需求文档(PRD)怎么写?阿里P8分享的模板+5个避坑点

作用:记录文档的版本、作者、评审信息,避免“文档混乱”。填写规范字段说明示例文档名称清晰反映产品名称,如“用户行为分析平台PRD”用户行为分析平台PRD_V1.0文档版本用“版本号+日期”,如V1.0_20240301编写人数据产品经理姓名+联系方式张三(138-XXXX-XXXX)评审人员业务负责人、开发经理、数据分析师、运维负责人李四(业务)、王五(开发)、赵六(数据)、周七(运维)评审时间评审日期2024-03-05评审意见。

架构师的AI之路,分享AI应用开发架构的学习与实践。 1571

LeetCode刷题笔录 Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key.Th

likecool21的专栏 6928

JQ8900语音播报模块在RT-Thread系统下的驱动移植与测试详解

本文详细讲解了如何在RT-Thread嵌入式操作系统中,为JQ8900语音播报模块进行驱动移植与功能测试。内容涵盖从获取驱动代码、配置Kconfig工程、编译烧录到核心代码解析的完整流程,并提供了基于串口通信的上电测试与问题排查方法,帮助开发者快速掌握在RT-Thread系统下集成外部模块的核心技能。

weixin_35677363的博客 593

Stanford Algorithms学习:Clustering 2

这是紧接上面的一道题,比较有趣 Question 2 In this question your task is again to run the clustering algorithm from lecture, but on a MUCH bigger graph. So big, in fact, that the distances (i.e., edge costs

likecool21的专栏 2567

MySQL——cost成本计算之MySQL如何选择使用索引(trace)

文章目录前言trace工具分析执行计划 前言 在之前博客中,根据测试案例,发现同样的sql语句,因为传入的条件值的不同,导致MySQL有时候选择使用索引,有时候又不适用索引。 如下所示sql的执行计划: EXPLAIN SELECT * FROM employees WHERE name > 'aaa'; EXPLAIN SELECT * FROM employees WHERE name > 'zzzz'; 在MySQL中,为什么会出现上述这种玄乎的现象呢? 本篇博客重点说明原因。 在说

专注写bug 679

Qt —— 在Win11下“Qt for Android“开发环境,通过USB在真机(华为Meta60 PRO)上调试运行,并打包APK并在真实手机运行

Qt —— 在Win11下“Qt for Android“开发环境,打包APK并在真实手机运行

310

Stanford Algorithms学习:Clustering

第二周的第一个编程作业,是利用贪婪算法来实现一个clustering的问题,和ML里学的unsupervised learning差不多。 Question 1 In this programming problem and the next you'll code up the clustering algorithm from lecture for computing a

likecool21的专栏 2507

GB 47955—2026 L2组合驾驶辅助强制国标全解、合规方案与工程代码落地

GB 47955—2026 L2辅助驾驶国标合规工程代码# 运行环境:Python3.8+,适配车载仿真、台架测试、算法验证场景# 依赖安装:pip install numpy dataclasses tqdm struct time json# ===================== 国标强制时序参数(完全对标GB 47955—2026) =====================HAND_OFF_FIRST_WARN = 5.0 # 手部脱离5s触发一级预警。

lin_xiu的博客 295

LeetCode 刷题笔录 Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a link

likecool21的专栏 1806

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

深度学习工具包 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刷题笔录Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word:

likecool21的专栏 1296

Camera2Demo

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

LeetCode刷题笔录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.

likecool21的专栏 1109

NTscan扫描工具

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

LeetCode刷题笔录Unique Binary Search Trees

这里有个讲解(印度人口音真难懂)

likecool21的专栏 1043

LeetCode刷题笔录 Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? 这题比较简单

likecool21的专栏 1043

LeetCode刷题笔录Container With Most Water

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Fin

likecool21的专栏 1001

LeetCode刷题笔录 Reverse Integer

Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 随手写的一个,正常的读出每一位的数字然后反序: import java.lang.Math; public class Solution { public int revers

likecool21的专栏 941

LeetCode刷题笔录Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the f

likecool21的专栏 865

LeetCode刷题笔录Convert Sorted Array to Balanced Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 这题可以kan'chu'lai

likecool21的专栏 855

求集合的交集/差集

先利用外部排序使两个磁盘文件有序,然后顺序读取两个文件,使用双指针求交集。在进阶 1 中,我们是通过双指针去做的,最坏情况下我们需要完整遍历。时,O(n log m) 可能明显优于 O(n + m)。的,这就使得我们可以通过从 1~1000 遍历来确定交集。,它们已经按非降序排序,请你返回两个数组的。和上一题的区别在于,这里需要找到重复的元素。返回一个数组,数组中的每个元素在。的每个字符串中都出现的共用字符(**注意:**列表中的整数可以按。较小,可以完整加载到内存,而。正整数组成的一个非空数组,按。

jyyyyx的算法之旅 111

LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)

LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等) 题目描述: 给定三个字符串 s1、s2、s3,请你帮忙验证 s3 是否是由 s1 和 s2 交错 组成的。 两个字符串 s 和 t 交错 的定义与过程如下,其中每个字符串都会被分割成若干 非空 子字符串: - s = s1 + s2 + ... + sn - t = t1 + t2 + ... + tm - |n - m| <= 1 - 交错 是 s1 + t

huayimenghan的博客 202

LeetCode 每日一题 2026/11/2-2026/11/8

记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步

AlphaTao的博客 175

LeetCode Hot 100 二叉树专题(二)3 题(Java)

本篇文章共 3 题:543. 二叉树的直径、102. 二叉树的层序遍历、108. 将有序数组转换为二叉搜索树。 每道题都统一按「① 题目分析 & 解题思路 → ② 常见解法(附代码)及讲解 → ③ 知识点总结」的顺序组织;代码使用 Java 编写,节点定义沿用 LeetCode 默认的 TreeNode。

2401_88612756的博客 360
上一篇: LeetCode刷题笔录Remove Nth Node from End of List
下一篇: LeetCode刷题笔录Search in Rotated Sorted Array
likecool21
博客等级 码龄14年 14粉丝 123原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值