【LeetCode_101】 对称二叉树

LeetCode101对称二叉树 算法特点及适用场景特点利用递归的思想巧妙地将判断二叉树是否对称的问题转化为比较对应子树是否对称相等的子问题,代码结构清晰简洁,逻辑上很符合二叉树这种具有递归结构的数据结构特点,易于理解和实现。通过层层递归比较节点值以及子树的对称性,能够准确地判断二叉树是否满足对称的性质。时间复杂度为 $O (n)`,在遍历二叉树节点判断对称性方面具有合理的效率表现,只要二叉树的节点数量在可接受范围内,都能较快地得出二叉树是否对称的结论。适用场景。 阅读详情

描述:

给定一个二叉树,检查它是否是镜像对称的。

示例:例如,二叉树 [1,2,2,3,4,4,3] 是对称的

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        return campSymm(root.left, root.right);
    }
    private boolean campSymm(TreeNode nodeLeft, TreeNode nodeRight) {
        if (nodeLeft == null && nodeRight == null) return true;
        if (nodeLeft == null 
        || nodeRight == null 
        || nodeRight.val != nodeLeft.val) {
            return false;
        }
        return campSymm(nodeLeft.left, nodeRight.right)
            && campSymm(nodeLeft.right, nodeRight.left);    
    }      
}

 

力扣(LeetCode) 101: 对称二叉树 - 解法思路 给定一个二叉树的根节点root,检查它是否是轴对称的(即,围绕其中心镜像对称)。左子树是右子树的镜像反射对应节点具有相同的值结构是镜像的两种方法都实现了 O(n) 时间复杂度。递归解决方案通常因其简单性而更受欢迎。对称树要求左子树是右子树的镜像,这意味着比较left.left与以及left.right与right.left。 阅读详情

相关推荐

【简单】力扣算法题解析LeetCode101:对称二叉树

本文探讨了如何判断二叉树是否对称的问题。通过递归和迭代两种方法实现:递归法通过比较左右子树的镜像关系(左左对右右,左右对右左)实现高效判断,时间复杂度O(n);迭代法则利用队列按层比较对称节点。两种方法均需处理空节点和值不等的边界条件。递归法代码简洁,适合小规模树;迭代法避免栈溢出,适合大规模数据。附Java实现代码及LeetCode提交结果,展示了两种方法的时间/空间复杂度对比。

ylumwd的博客 454

LeetCode 101.对称二叉树(DFS、BFS)

给定一个二叉树,检查它是否是镜像对称的。

晴空๓ 5232

LeetCode——101,对称二叉树

/** * \* Created: liuhuichao * \* Date: 2019/8/22 * \* Time: 35:53 AM * \* Description: 对称二叉树 * 给定一个二叉树,检查它是否是镜像对称的。 * <p> * 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 * <p> * 1 * / \ * ...

我们的征途是星辰大海 669

LeetCode 101 ----- 对称二叉树

LeetCode 101 ----- 对称二叉树 题目描述 给定一个二叉树,检查它是否是镜像对称的。 思路 **对称,可以看做镜像 根节点为 null,则为对称二叉树 如果两个数都是空树,算镜像 两个数一个为空,有个非空,则不是镜像 如果两个树都不为空 a)比较根节点是不是相同,不相同就不是镜像 b)递归比较子树,t1.left 和 t2.right , t1.right 和 t2.left 是...

lsy18392609095的博客 170

px3 有感分析

px3 后续分析

qq_39707917的博客 3115

从零开始:使用Labelme完成图像语义分割标注全流程

本文详细介绍了如何使用Labelme工具完成图像语义分割标注的全流程,从环境安装、数据准备到核心标注操作,并重点讲解了如何将标注结果转换为PASCAL VOC等深度学习框架可用的标准数据集格式。文章还提供了关键的避坑指南和高效技巧,帮助初学者快速上手,高效产出高质量的标注数据。

weixin_29073241的博客 491

LeetCode 力扣 101. 对称二叉树

题目描述(简单难度) 判断一个二叉树是否关于中心轴对称。 解法一 和 100 题 判断两个二叉树是否相等其实是一样的思路,都是用某种遍历方法来同时遍历两个树,然后看是否对应相等。 这里的需要遍历的两个树就是左子树和右子树了。 这里的对应相等的话,因为判断左子树 A 和右子树 B 是否对称,需要判断两点。 A 的根节点和 B 的根节点是否相等 A 的左子树和 B 的右子树是否相等,同时 A 的右...

wind_liang的博客 906

基于Plecs的LLC谐振变换器闭环设计:从PI参数整定到动态响应优化

本文详细介绍了在Plecs仿真环境中,如何为半桥LLC谐振变换器设计并优化闭环控制系统。从开环模型搭建与特性分析入手,重点阐述了基于频域法的PI控制器参数整定流程,并通过负载阶跃、输入电压突变等测试优化动态响应。文章还分享了从仿真模型过渡到实际硬件时的关键注意事项,帮助工程师实现稳定、高效的电源设计。

e4f5g6h的博客 623

101. 对称二叉树【 力扣(LeetCode) 】

给你一个二叉树的根节点 root , 检查它是否轴对称。进阶:你可以运用递归和迭代两种方法解决这个问题吗?

yyh520025的博客 1234

交叉编译Qt6.5.3(RK3568开发板)

注意,如果使用其它版本的交叉编译器的话,请确保你的交叉编译器能够支持 C++17标准。为确保后续交叉编译没问题,需要确保开发板使用的GLIBC版本不小于2.34版本。到 linaro 网站上下载交叉编译工具,我下载的是 gcc-linaro-11.3.1-2022.06-x86_64_aarch64-linux-gnu.tar.xz。安装 CMake ,最低要求3.16版本,如果要静态编译,需要3.21及以上版本。我使用的3.27版本。:指定为最后交叉编译后的Qt6.5.3库的安装目录。

m0_46309425的博客 5101

FLUENT UDF编译及蒸发冷凝相关问题

蒸发冷凝与相间传质

weixin_48029137的博客 1万+

瑞_力扣LeetCode_101. 对称二叉树

本文章为瑞_系列专栏之《刷题》的力扣LeetCode系列,主要以力扣LeetCode网的题进行解析与分享。力扣LeetCode_101. 对称二叉树

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

告别代码恐惧!用KRobot图形化编程,10分钟搞定Arduino巡线小车(附完整接线图)

本文介绍如何使用KRobot图形化编程工具快速搭建Arduino巡线小车,无需编写代码。从硬件准备到逻辑构建,详细讲解传感器数据处理、电机控制优化及高级功能扩展,帮助教育工作者和创客爱好者10分钟内完成项目。

weixin_30632089的博客 394

Leetcode 101. 对称二叉树

Leetcode 101. 对称二叉树1、问题分析2、问题解决3、总结 1、问题分析 题目链接:https://leetcode-cn.com/problems/symmetric-tree/   本质上就是一个二叉树的深度优先搜索问题。代码我已经进行了详细的注释,理解应该没有问题,读者可以作为参考,如果看不懂(可以多看几遍),欢迎留言哦!我看到会解答一下。 2、问题解决   笔者以C++方式解决。 #include "iostream" using namespace std; #include "a

珍惜 8861

CosyVoice语音合成使用教程

CosyVoice是一款开源的语音合成工具,它基于深度学习模型,能够生成高度逼真的语音内容。该工具支持多种语言的语音生成,包括中文、英文、日文、粤语和韩语。CosyVoice的亮点在于它对生成语音情感和韵律的精细控制,通过富文本或自然语言输入,可以显著提升合成语音的情感表达能力。CosyVoice提供了多种预训练模型,用户可以根据需求选择合适的模型。:基底模型,适用于一般语音合成任务。:经过SFT微调的模型,适用于特定音色和情感的语音合成。:支持Instruct微调的模型,适用于自然语言控制的语音合成。

笔者从事电信媒体开发多年,愿意将多年的开发经验分享给同行 4442

14、微电网控制方法与建模分析

本文详细探讨了微电网的控制方法与建模分析,包括逆变器的小信号状态空间模型、网络模型、负载模型及其组合形成的完整微电网模型。通过对系统特征值和灵敏度因子的分析,揭示了不同模式与系统参数之间的关系。文章还提出了多个研究问题,如岛式系统控制器设计、风力发电控制、并网变换器控制等,为微电网的稳定性分析和优化控制提供了理论支持和实践方向。

elastic6hunter的博客 123

力扣 101 对称二叉树【递归三步法】

力扣 101 对称二叉树【递归三步法】 文章目录力扣 101 对称二叉树【递归三步法】全部刷题与学习记录原题目考查知识点自己的第一遍解法好的解法 全部刷题与学习记录 【C++刷题学习笔记目录】 【C++百万并发网络通信-笔记目录】 原题目 题目地址:101. 对称二叉树 给定一个二叉树,检查它是否是镜像对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 但是下面这个 [1,2,2,null,3,null,3

日月既往,不可复追 485

Statistics and Machine Learning Toolbox

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

【力扣】101.对称二叉树

力扣 101题对称二叉树 c++解法

Father_Of_Soft的博客 315

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

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

《LeetCode力扣练习》第101题 对称二叉树 Java

《LeetCode力扣练习》第101题 对称二叉树 Java 一、资源 题目: 给你一个二叉树的根节点 root , 检查它是否轴对称。 示例 1: 输入:root = [1,2,2,3,4,4,3] 输出:true 示例 2: 输入:root = [1,2,2,null,3,null,3] 输出:false 提示: 树中节点数目在范围 [1, 1000] 内 -100 <= Node.val <= 100 进阶:你可以运用递归和迭代两种方法解决这个问题吗? 来源:力扣(LeetC

XRT_knives的博客 297

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

LeetCode 101. 对称二叉树

🌈🌈😄😄 欢迎来到茶色岛独家岛屿,本期将为大家揭晓LeetCode 101. 对称二叉树,做好准备了么,那么开始吧。 🌲🌲🐴🐴

weixin_62275996的博客 760

LeetCode 101对称二叉树

LeetCode 101对称二叉树 题目简述:给定一个二叉树,检查它是否是镜像对称的。 二叉树 [1,2,2,3,4,4,3] 是对称的,但是 [1,2,2,null,3,null,3] 则不是镜像对称的 思路:递归O(n) 两个子树互为镜像当且仅当: 两个子树的根节点值相等; 第一棵子树的左子树和第二棵子树的右子树互为镜像,且第一棵子树的右子树和第二棵子树的左子树互为镜像; class Solution { public: bool cmp(TreeNode* p, TreeN

XBlog 168

LeetCode101(力扣101):对称二叉树 C++

101.对称二叉树 给定一个二叉树,检查它是否是镜像对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1 / \ 2 2 \ \ 3 3 进阶: 你可以运用递归和迭代两种方法解决这个问题吗? 我提交的代码 class Solution { public: bool isDCtre

VegetableGirl的博客 507

LeetCode第101题_对称二叉树

给你一个二叉树的根节点root,检查它是否轴对称。

qq_40263592的博客 1022

Leetcode101:对称二叉树

Java,若左子树的左孩子和右子数的右孩子不相等或左子树的右孩子和右子数的左孩子不相等,就返回false。给你一个二叉树的根节点 root , 检查它是否轴对称。

qq_52726736的博客 255

101. 对称二叉树 - 力扣(LeetCode)

和100题一样的思想,只不过传入方式不同,同时传入的left和right总是轴对称的,和100题处于同一个位置一样。

xxm919的博客 140

力扣 101. 对称二叉树

以上就是今天要讲的内容,本文简单介绍了 力扣 101. 对称二叉树 的解题思路,在力扣以及牛客网中还会有很多类似的题目,今后将会持续更新,敬请关注!

m0_73724954的博客 184
上一篇: 【LeetCode_69】 x 的平方根
下一篇: 【LeetCode_107】二叉树的层次遍历 II
West Money
博客等级 码龄9年 7粉丝 48原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值