Leetcode 617. Merge Two Binary Trees

CentOS8安装NVIDIA显卡驱动、CUDA和Anaconda CentOS8安装NVIDIA显卡驱动和CUDA 参考:CentOS nvidia+cuda+cudnn 安装 安装英伟达显卡驱动 1、检查是否安装了NVIDIA的GPU(硬件层面): lspci | grep -i nvidia 2、安装GCC、kernal组件、dkms等 sudo yum install gcc sudo yum install gcc-c++ sudo yum -y install kernel-devel sudo yum -y install kernel-headers s 阅读详情

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
Note: The merging process must start from the root nodes of both trees.

一道很简单的有关树的遍历的题。题意就是要合并两棵树,相同位置的节点的值相加。同样是用递归来做,自己的想法还是显得复杂许多。最后面给出了大神写的代码,只有几行代码简洁又优雅。
也很好理解,若有一个树为空,则直接接上另外一个树的余下部分,若两个树都不为空,则把值相加。

class Solution {
public:
    TreeNode* result;
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        TreeNode * res;
        travel(result,t1,t2);

        return result;
    }
    void travel(TreeNode* &res,TreeNode *x,TreeNode *y) {
        int val1=0, val2=0;

        if (x == NULL&&y==NULL) {
            return;
        } 
        if (x == NULL) {


            res = new TreeNode(y->val);
            travel(res->left, NULL, y->left);
            travel(res->right, NULL, y->right);
        }else if (y == NULL) {

            res = new TreeNode(x->val);
            travel(res->left, x->left, NULL);
            travel(res->right, x->right, NULL);
        }
        else {
            res = new TreeNode(x->val+y->val);
            travel(res->left, x->left, y->left);
            travel(res->right, x->right, y->right);
        }


    }
};
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if (!t1) return t2;
        if (!t2) return t1;

        TreeNode* node = new TreeNode(t1->val + t2->val);
        node->left = mergeTrees(t1->left, t2->left);
        node->right = mergeTrees(t1->right, t2->right);
        return node;
    }
};
ADS新手必看:ICCAP数据导入与导出CSV的完整流程(附常见问题解决) 本文为ADS新手详细讲解了如何将ICCAP测试数据导入ADS进行仿真分析,并导出为通用CSV格式的完整流程。内容涵盖文件格式解析、导入设置、数据验证、处理技巧及常见问题排查,重点解决了数据文件导入过程中的兼容性与单位映射等核心难点,帮助射频工程师高效连接测量与仿真环节。 阅读详情

相关推荐

RagFlow 文档解析

RAGFlow 的设计哲学是“高质量输入,高质量输出”,它通过提供可解释性和可控性的生成结果,让用户能够信任并依赖于系统提供的答案。

weixin_43008312的博客 3998

Leetcode学习笔记:#617. Merge Two Binary Trees

Leetcode学习笔记:#617. Merge Two Binary Trees Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You ...

ccystewart的博客 155

Python头歌实验题目(2024版)

武汉理工大学头歌平台实验题目

2401_84152595的博客 2万+

[Leetcode]617. Merge Two Binary Trees

[Leetcode]617. Merge Two Binary Trees

正西风落叶下长安 1749

TP4054充电电路发热严重?手把手教你调整电阻值降低温度(附实测数据)

本文针对TP4054锂电池充电电路发热严重的问题,提供了详细的排错与解决方案。通过分析发热原理,指出核心在于PROG引脚电阻值设定,并手把手指导如何计算和选择正确的电阻以降低充电电流与温度。文末附有不同电阻下的实测温度与性能数据,为电子爱好者和工程师提供了实用的调试参考。

p4q5r6s7t的博客 406

HITS算法详解及代码实现

占坑

蓁蓁尔的博客 7461

leetcode 617. Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tr

淡然坊 497

手把手教你排查Abaqus中的Johnson-Cook损伤参数:避免因d3正负号导致的仿真失败

本文详细解析了Abaqus中Johnson-Cook损伤参数d3正负号设置的关键问题,帮助用户避免因参数错误导致的仿真失败和Excessive distortion报错。通过对比不同文献定义、提供实操指南和典型错误排查流程,有效提升非线性分析的准确性和效率。

weixin_33960567的博客 353

【LeetCode】617. Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree...

韩旭051的博客 635

小米15修复“NV损坏” 去除主板校验电阻步骤解析与图示

小米15系列将搭载骁龙8至尊版处理器,采用台积电3nm工艺。文章分析了手机出现"NV损坏"故障的表现及修复方法,包括通信异常、系统启动问题等典型症状,并介绍了去除主板校验电阻和刷写工程固件两种修复方案。重点讲解了去除主板电阻后刷写QCN文件的操作流程,强调在维修过程中需要结合分析与思考。适用于小米15系列特定机型(24129PN74G/I/C)的硬件修复。

小马哥的专栏 312

【SpringBoot 4.x 第2节】夯爆了,学习 Spring Boot 4.x 前,需要具备哪些 Java 基础?

🏆 本文收录于 《滚雪球学 Spring Boot 4.x》 专栏。 本专栏面向 有一点 Java 基础,但没有系统学过 Spring Boot 的读者,采用“滚雪球式学习法”:先跑通、再理解、再重构、再上线,最终带你从第一个 Hello API 一路完成一个可部署、可监控、可扩展的后端项目。

**My Coding Family** 4566

LeetCode //C - 617. Merge Two Binary Trees

【代码】LeetCode //C - 617. Merge Two Binary Trees。

Made in Code 1133

【网络安全 | 渗透工具】密码字典生成工具crunch、cupp安装使用教程

Crunch是一个常用的密码破解工具,它可以根据指定的字符集、长度和模式生成各种可能的密码并进行暴力破解。同时,Crunch可以将生成的密码保存到文件中,以便在破解工具中使用。在进行渗透测试时,手动收集密码字典是十分耗时的,利用密码字典生成工具可以大幅缩短时间,提高爆破宽度。

等风来 8421

LeetCode 617. Merge Two Binary Trees

LeetCode 617. Merge Two Binary Trees题目大意:根据已给的二叉树,将相对应位置的值相加,获得合并后的二叉树。(空值相当于0)-Example:Input: Tree 1 Tree 2 1 2

Cecilia_whf的博客 824

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

深度学习工具包 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] 617. Merge Two Binary Trees

原题链接:https://leetcode.com/problems/merge-two-binary-trees/ 1. 题目介绍 Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while...

Ber03的博客 218

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

【Leetcode 617】Merge Two Binary Trees -EASY

【Leetcode 617】Merge Two Binary Trees - EASY题目示例: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20190316201010341.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLm...

weixin_43621681的博客 388

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Leetcode——617. Merge Two Binary Trees

题目原址 https://leetcode.com/problems/merge-two-binary-trees/description/ 题目描述 Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are over...

想当厨子的程序媛 334

Leetcode 617 Merge Two Binary Trees

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { pub...

Polanwind 114

LeetCode:617. Merge Two Binary Trees

LeetCode:617. Merge Two Binary Trees Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need...

Wisimer 197

LeetCode: 617. Merge Two Binary Trees

LeetCode: 617. Merge Two Binary Trees Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

qha0731的专栏 326

617. Merge Two Binary Trees python leetcode

617. Merge Two Binary TreesDescriptionHintsSubmissionsDiscussSolutionPick OneGiven two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overla...

一名路过的小码农啊 620

[LeetCode] 617.Merge Two Binary Trees

[LeetCode] 617.Merge Two Binary Trees 题目描述 解题思路 实验代码 题目描述Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others

user_name_is_so_long的博客 234

leetcode.617.Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

RaymondWong的博客 838

Leetcode617. Merge Two Binary Trees (C++)

Leetcode617. Merge Two Binary Trees 简单题,迭代比递归复杂一点点 代码如下: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeN

无远弗届 252

python leetcode 617. Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.You need to merge them into a new binary tree. ...

DreamerLHQ的博客 680

Leetcode 617. Merge Two Binary Trees(python)

Leetcode 617. Merge Two Binary Trees题目解法1:DFS解法2:BFS 题目 解法1:DFS 在recursion的每一步 如果当前的两个节点都不为空,更新第一棵树的当前节点val为两个节点val的和 如果其中有一个节点为空,则返回另一个节点 当前节点的left和right节点为下一层recursion返回的结果 class Solution(object)...

qq_37821701的博客 390
上一篇: LeetCode 647 Palindromic Substrings
下一篇: Leetcode 452 .Minimum Number of Arrows to Burst Balloons
wenkun97
博客等级 码龄10年 15粉丝 139原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值