LeetCode (65):Same tree

Total Accepted: 83663 Total Submissions: 200541 Difficulty: Easy

 Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

 

首先想到的是递归法,判断过程为依次遍历每一个点如果有:

  1. 如果都为null或是都不为null且值相等返回true
  2. 一个为Null另一个不为Null返回false
  3. 两个都不为null但值不相等返回false

代码如下:

class TreeNode{
       int val;
            TreeNode left;
           TreeNode right;
            TreeNode(int x) { val = x; }
}
public class Solution {
     public static boolean isSameTree(TreeNode p, TreeNode q) {
         if(p==null&&q==null)     return true;  //同时到达叶子节点
         else  if(p==null||q==null) return false;   //不同时到达叶子则不相同
         if(p.val!=q.val) return false;  //节点值不同则不相同
         else return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right); //递归
                                                                    
     }
           //测试
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TreeNode t1=new TreeNode(1);
        TreeNode nodeB=new TreeNode(2);
        t1.left=nodeB;
        
        TreeNode t2=new TreeNode(1);
        TreeNode nodeB1=new TreeNode(2);
        t2.left=nodeB1;        
        System.out.println(isSameTree(t1,t2));
    }

}

 

转载于:https://www.cnblogs.com/rever/p/4853823.html

利用pyGAM实现广义可加模型(GAM)的实战指南 本文提供了利用pyGAM库实现广义可加模型(GAM)的完整实战指南。通过乳腺癌和房价预测案例,详细讲解了从环境配置、模型构建、核心可视化(部分依赖图)到参数调优(n_splines, lam)的每一步。重点展示了GAM如何平衡模型准确性与可解释性,帮助数据科学家在Python中高效应用这一强大工具。 阅读详情

相关推荐

基于R语言的DICE模型实践技术应用;预测不同减排路径下的经济增长、碳排放量、气候变化程度以及社会福利变化

DICE模型是一个动态综合气候经济模型,由诺贝尔经济学奖得主William Nordhaus开发,用于评估气候变化对经济的影响以及不同减排政策的经济成本和效益。以下是一个关于DICE模型在气候变化影响评估中的实际应用案例,结合R语言代码进行讲解。

KY_chenzhao的博客 871

leetcode 65: Same Tree

Same TreeSep 3 '12 Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the

西施豆腐渣 5988

Windows 10下Carla 0.9.15安装避坑指南:从下载到运行的全流程解析

本文详细解析了在Windows 10系统上安装和运行Carla 0.9.15自动驾驶仿真平台的全流程。内容涵盖从系统环境准备、资源下载、Python依赖安装,到首次启动验证及常见错误(如DLL缺失、显卡驱动问题)的深度解决方案,旨在帮助用户快速搭建稳定的开发环境,并运行第一个自动驾驶Python脚本。

alice7model的博客 554

【LeetCode】65. Same Tree

题目描述(Easy) Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same valu...

YTea的博客 108

docker安装fastdfs+nginx配置

docker安装fastdfs+nginx,实现图片或文件的上传与下载

weixin_47325126的博客 2195

尚硅谷Redis 7学习笔记

尚硅谷Redis 7学习笔记

不更了,主打一个陪伴 2万+

LeetCode之“树”:Symmetric Tree && Same Tree

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 / \ ...

137

2006NOIP普及组真题 4. 数列

从上述推理中,我们发现要输出的幂次和中的第 N 项(也就是幂次和中的序号N),对应的二进制位数和幂次和对应的二进制位数相同。当 k=3 时,k的幂次为1, 3, 9, 27, 81…,即第0位,第2位均为1,转成 k 进制(k=3)时。,即第2位,第3位均为1,转成 k 进制(k=3)时。转成 k 进制(k=3)时的幂次和为。,即第0位,第1位,第2位均为1,(即第0位,第1位,第2位均为1)N=12时,12的二进制是。(即第0位,第2位均为1)(即第2位,第3位均为1)结论:这道题就变成了。

weixin_40252159的博客 1517

LeetCode OJ - Symmetric Tree && Same Tree

这两道题,大同小异。 我都是用BFS,在遍历的过程,判断结构是否相同/对称,值是否相同。 下面是AC代码: 1 /** 2 * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 3 * @param root ...

weixin_33997389的博客 145

[工作流节点10] 获取多条数据并循环执行 —— 明道云批处理自动化实战

本文系统介绍了明道云工作流中"获取多条数据+循环执行"的批处理功能。该功能通过筛选数据集合并逐条处理,适用于批量通知、数据更新等场景。文章详细解析了功能配置方法,包括数据筛选、循环设置和异常处理,并提供了合同到期提醒等典型应用案例。同时强调了数据量控制、分批处理、错误处理等优化策略,帮助用户实现高效批量自动化。这一功能组合能将业务从单条处理升级为批量驱动,显著提升工作效率。

每日出拳老爷子的博客 471

Yocto开发讲解系列 - 总目录

Yocto开发讲解系列总纲Yocto开发专栏前言

fulinux的博客 3万+

leetcode 刷题之路 65 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

600

基于STM32的DS1302电子时钟电路与程序设计

这个示例代码中,我们使用DS1302_GetTime函数从DS1302芯片获取当前时间,并使用DS1302_GetDate函数获取当前日期。在本文中,我们将介绍如何使用STM32微控制器和DS1302实时时钟芯片来构建一个基于STM32的DS1302电子时钟,并提供相应的程序设计。请注意,以上示例代码仅供参考,具体的实现细节可能会根据使用的开发环境和硬件组件有所差异。在实际应用中,你可能需要根据自己的需求进行适当的调整和修改。为了完整实现电子时钟的功能,你还可以添加其他功能,例如闹钟设置、温度显示等。

UbiSqlserver的博客 1334

Recover Binary Search Tree

Recover Binary Search Tree threaded binary tree 1 public class Solution { 2 public void recoverTree(TreeNode root) { 3 ...

94

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

深度学习工具包 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 (Binary Tree) -- Day 65 & Day 70

Leetcode (Binary Tree) -- Day 65 & Day 70 Question 1 Binary Tree Preorder Traversal Given a binary tree, return thepreordertraversal of its nodes' values. F...

weixin_30590285的博客 89

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

[leetcode: Python]543. Diameter of Binary Tree

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may no

cyy2learn的博客 2088

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

leetcode 814. Binary Tree Pruning(python)

就是使用的 DFS ,判断最底层的节点的左子树是否为空,右子树是否为空,如果左右子树都为空且值为 0 的节点,那么将其变为空。然后向上回溯,上层的节点通过同样的方法也能变为空,知道最后将所有节点从下到上都判断一次,然后返回新树的根节点。根据题意,就是给出了一个二叉树 root ,然后让我们进行树的剪枝,对不包含 1 的子树进行移除,返回移除了节点后的树的索引。原题链接:https://leetcode.com/problems/binary-tree-pruning/您的支持是我最大的动力。

王大呀呀的博客 301

LeetCode: Symmetric Tree 解题报告

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  3But the foll...

weixin_34021089的博客 129

LeetCode 863. All Nodes Distance K in Binary Tree

原题链接在这里:https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/ 题目: We are given a binary tree (with root noderoot), atargetnode, and an integer valueK. Return a list of the values o...

weixin_30642305的博客 157

Leetcode 261: Graph Valid Tree

Givennnodes labeled from0ton - 1and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. For example: Givenn = 5an...

weixin_30520015的博客 139

[leetcode: Python]104. Maximum Depth of Binary Tree

题目: Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.方法一:性能65ms# Definition for a binary tr

cyy2learn的博客 644

LeetCode-105从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal)

LeetCode-105 Given preorder and inorder traversal of a tree, construct the binary tree. Example input: preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] return: [3,9,20,null,null,15,7]  &nbsp...

V2beach的博客 306

[LeetCode] Maximum Binary Tree

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed...

weixin_30763397的博客 145

基数树(radix tree)

目录 一,基数树(radix tree) 二,OJ实战 CSU 1216: 异或最大值 CSU 1323: ZZY and his little friends(异或最大值) 一,基数树(radix tree) 基数树和字典树差不多,只不过字典树的基本单位是字符,一般一个节点有大约26个或52个子节点,而基数树的基本单位是若干比特位。 思路: 无论S是结构体还是整数,都直接当做若干比特位,每x个比特位划分为一份,一共len/x份,len是S的比特数 每个节点需要2^x个指针或者整数,每一个

nameofcsdn的博客 2129
上一篇: LeetCode (237):Delete Node in a Linked List
下一篇: LeetCode (226):Invert Binary Tree 递归实现
dixie2009
博客等级 码龄11年 3粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值