【算法入门14】二叉树的镜像

一篇学会二叉树的镜像 一篇学会二叉树的镜像???? 二叉树镜像定义: 对于二叉树中任意节点 root ,设其左 / 右子节点分别为 left, right;则在二叉树的镜像中的对应 root节点,其左 / 右子节点分别为 right, left 。 Leetcode : https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof “GitHub : https://github.com/nateshao/leetcode/blob/main/algo-n 阅读详情

核心考点:二叉树操作

操作给定的二叉树,将其变换为源二叉树的镜像。
在这里插入图片描述
解析:
要将一棵二叉树变化为自身的镜像,只需交换该二叉树每一个结点的左右子树即可。

例如,上述二叉树我们交换根结点的左右子树后源二叉树会发生如下变化。
在这里插入图片描述
再继续交换下一层结点的左右子树后,便可得到源二叉树镜像后的二叉树。
在这里插入图片描述
但实际上我们还会交换叶子结点的左右子树,只不过叶子结点的左右子树都为空树交换后二叉树无变化。

二叉树都是递归定义的,所以递归操作是比较常见的做法。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};*/
class Solution {
public:
	TreeNode* Mirror(TreeNode* pRoot) {
		if (pRoot == nullptr) //空树无需镜像
			return nullptr;
		TreeNode* left = Mirror(pRoot->left); //将该结点的左子树镜像
		TreeNode* right = Mirror(pRoot->right); //将该结点的将右子树镜像
		//交换该结点的左右子树
		pRoot->left = right;
		pRoot->right = left;
		return pRoot; //返回该结点
	}
};

但该题目我们只需要将二叉树所有结点的左右子树进行交换即可,所以只要是能遍历二叉树的方法我们都可以使用,下面给出了使用队列和栈解决的方法。

使用队列遍历二叉树进行各结点左右子树的交换。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};*/
class Solution {
public:
	TreeNode* Mirror(TreeNode* pRoot) {
		if (pRoot == nullptr) //空树无需镜像
			return nullptr;
		queue<TreeNode*> q;
		q.push(pRoot); //先将根结点入队列
		while (!q.empty())
		{
			//取队头结点
			TreeNode* pNode = q.front();
			q.pop();
			//交换该结点的左右子树
			TreeNode* temp = pNode->left;
			pNode->left = pNode->right;
			pNode->right = temp;
			//若该结点的左结点不为空,则将其左结点入队列
			if (pNode->left)
				q.push(pNode->left);
			//若该结点的右结点不为空,则将其右结点入队列
			if (pNode->right)
				q.push(pNode->right);
		}
		return pRoot; //返回根结点
	}
};

使用栈遍历二叉树进行各结点左右子树的交换。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};*/
};
class Solution {
public:
	TreeNode* Mirror(TreeNode* pRoot) {
		if (pRoot == nullptr) //空树无需镜像
			return nullptr;
		stack<TreeNode*> st;
		st.push(pRoot); //先将根结点入栈
		while (!st.empty())
		{
			//取栈顶结点
			TreeNode* pNode = st.top();
			st.pop();
			//交换该结点的左右子树
			TreeNode* temp = pNode->left;
			pNode->left = pNode->right;
			pNode->right = temp;
			//若该结点的左结点不为空,则将其左结点入栈
			if (pNode->left)
				st.push(pNode->left);
			//若该结点的右结点不为空,则将其右结点入栈
			if (pNode->right)
				st.push(pNode->right);
		}
		return pRoot; //返回根结点
	}
};
二叉树的镜像 题目描述 操作给定的二叉树,将其变换为源二叉树的镜像。 输入描述: 二叉树的镜像定义:   源二叉树 镜像二叉树 8 8 / \ / \ 6 10 10 6 / \... 阅读详情

相关推荐

Python算法——树的镜像

这表示在给定的二叉树上,经过镜像处理后,左右子树的位置交换了,得到了一棵新的树。树的镜像在一些应用中很有用,例如判断两棵树是否对称等。通过理解算法的原理和实现,您将能够更好地处理树结构问题。树的镜像是指将树的每个节点的左右子树交换,得到一棵新的树。在本文中,我们将深入讨论如何实现树的镜像算法,提供Python代码实现,并详细说明算法的原理和步骤。树的镜像可以通过递归遍历树的每个节点,交换其左右子树来实现。递归的终止条件是遇到null节点,此时无需进行交换。

Echo_Wish 383

JZ27 二叉树的镜像

题目: 操作给定的二叉树,将其变换为源二叉树的镜像。 数据范围:二叉树的节点数0 \le n \le 10000≤n≤1000, 二叉树每个节点的值0\le val \le 10000≤val≤1000 要求:空间复杂度O(n)O(n)。本题也有原地操作,即空间复杂度O(1)O(1)的解法,时间复杂度O(n)O(n) 比如: 源二叉树 镜像二叉树 我的结果: 借助了堆栈。 /** * struct TreeNode { * int val; *...

qq_42082542的博客 1700

Astah 9.0升级步骤(Widnows/Mac OS)

Astah Professional是一款全新的轻量级UML建模工具。软件集思维导图和UML建模于一体,采用100%纯JAVA构建, 兼容性强,不仅能够实现分布式建模、项目合并,还能够实现和其它建模工具的交互。

tequiero777的博客 2824

每日算法题 | 剑指offer 二叉树专题 (14) 二叉树的镜像

点击上方“Jerry的算法和NLP”,选择“星标”公众号 重磅干货,第一时间送达题目二叉树的镜像题目要求 操作给定的二叉树,将其变换为源二叉树的镜像。解题思路存在三种...

Jerry的编程之路 172

InsightFace(RetinaFace + ArcFace)人脸识别实战:从模型部署到Web服务构建

本文详细介绍了如何利用InsightFace框架,结合其集成的RetinaFace人脸检测与ArcFace人脸识别预训练模型,从零开始构建一个高性能的Web人脸识别服务。内容涵盖环境搭建、模型部署、核心代码解析(包括五点仿射对齐关键步骤)、FAISS向量检索集成以及基于FastAPI的Web服务开发,并提供了实战优化与常见问题排查指南,帮助开发者快速实现工业级应用。

weixin_29054245的博客 225

ClearML中文文档实战:从安装到第一个实验的保姆级教程

本文提供ClearML从零开始的实战指南,涵盖核心组件理解、Python SDK安装、服务器配置及首个自动化实验的完整流程。通过改造PyTorch训练脚本的实例,详细演示了如何利用ClearML自动记录实验参数、指标与模型,实现机器学习实验的可复现性与高效管理,并简要介绍了进阶的自动化工作流。

weixin_29216049的博客 398

14、操作给定的二叉树,将其变换为源二叉树的镜像。

二叉树的镜像定义:源二叉树 8 / 6 10 / \ / 5 7 9 11 镜像二叉树 8 / 10 6 / \ / 11 9 7 5 方法:简单的递归即可 /* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x...

weixin_44139400的博客 175

中移物联ML307C模组OPENCPU开发环境搭建全攻略

本文详细介绍了中移物联ML307C模组OPENCPU开发环境搭建的全过程。从OPENCPU模式的核心优势解析,到SDK获取、Python与scons工具安装,再到解读SDK目录结构与实战编译命令,最后提供常见问题避坑指南,帮助开发者快速构建高效的物联网应用编译环境。

weixin_29168393的博客 743

剑指offer-二叉树的镜像实现

/******************************************************************* Copyright(c) 2016, Tyrone Li All rights reserved. *******************************************************************/ // 作者:Tyron...

OliverkingLi的博客 272

快速玩转 Llama2!机器学习 PAI 最佳实践(一)—低代码 Lora 微调及部署

本实践将采用阿里云机器学习平台PAI-快速开始模块针对 Llama-2-7b-chat 进行开发。PAI-快速开始支持基于开源模型的低代码训练、布署和推理全流程,适合想要快速开箱体验预训练模型的开发者。

阿里云云栖号 1766

Rk3128投影仪救砖操作和固件分享思路

大家搞一条比较硬的东西,插入耳机口,就可以进入刷机模式了的,我的机器是这样的,大家也可以试试。(看不懂可以往下看)

MMX7088的博客 1万+

14.对称二叉树

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。 例如,二叉树[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 示例 1: 输入:root = [1,2,2,3,4,4,3] 输出:true 示例 2: 输入:ro...

qq_33776188的博客 373

深入Netflix影片分类数据抓取的Python爬虫实战:反反爬机制绕过与Playwright应用全解析

技术工具用途Playwright控制真实浏览器模拟用户行为开发语言asyncio异步调度浏览器任务pandas数据处理和导出sqlite3本地数据库存储支持随机UA模拟,增强反爬能力为什么选择 Playwright?✅ 支持多浏览器(Chromium、Firefox、WebKit)✅ 原生支持 Python 异步编程✅ 提供截图、滚动模拟、验证码处理等高级功能✅ 反爬能力强,模拟真实用户访问。

2201_76125261的博客 1239

剑指offer18:操作给定的二叉树,将其变换为源二叉树的镜像。

1 题目描述   操作给定的二叉树,将其变换为源二叉树的镜像。 2 输入描述: 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / ...

AMY100727的博客 296

ThingsBoard教程(十九):规则节点概览介绍

在ThingsBoard的CE V2.5.6版本中,一共有这几种类型在每一种类都有包含了多个节点,每一种类型的节点都有不同的颜色表示本篇文章做一个简单的概括,后续的文章会详细讲解每一个种类的节点如何使用,每一个节点的使用。一共有10个,使用黄色表示 过滤器节点用于消息过滤和路由。一共有9个,使用绿色 属性节点用于更新传入消息的元数据。一共三个,使用蓝色 转换节点用于更改传入消息字段,如发起者、消息类型、有效负载和元数据。一共21个,使用红色标识 动作节点根据传入的消息执行各种动作。一共9个,使用黄色表示,

知无涯 1万+

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

二叉树镜像

【题目描述】 操作给定的二叉树,将其变换为源二叉树的镜像。 输入描述: 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ ...

aebvyzx53246的博客 99

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

剑指offer——二叉树的镜像

题目:操作给定的二叉树,将其变换为源二叉树的镜像。 思路:前序(根左右的顺序)遍历一棵树,在存储的时候将其左右树进行交换,最后按照处理后的树还原,即得到其镜像。 1 /** 2 public class TreeNode { 3 int val = 0; 4 TreeNode left = null; 5 TreeNode right = null...

weixin_34292924的博客 75

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

STM32F407中文手册

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

剑指Offer 27 二叉树的镜像

二叉树的镜像 操作给定的二叉树,将其变换为源二叉树的镜像。 1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = ...

weixin_34378045的博客 94

剑指offer-二叉树的镜像

题目描述:操作给定的二叉树,将其变换为源二叉树的镜像。 输入描述: 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ ...

108

算法:二叉树镜像

问题:操作给定的二叉树,将其变换为源二叉树的镜像。思路:采用递归的方法,1:空二叉树直接return;定义节点temp;2:判断节点为非空;借助temp执行根节点左右值的交换;3: 判断根节点的左右节点非空,对节点进行递归; package LG.nowcoder; /** * @Author liguo * @Description 二叉树的镜像 * @问题:操作给定的二...

weixin_34319999的博客 160

剑指Offer 二叉树的镜像

题目描述 操作给定的二叉树,将其变换为源二叉树的镜像。 输入描述: 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ ...

72
上一篇: 【算法入门13】树的子结构
下一篇: Linux进程间通信
2021dragon
2021dragon 2021年博客新星Top3 2021年博客新星Top3
博客等级 码龄6年 4万+粉丝 277原创
评论 11
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

2021dragon

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

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

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

打赏作者

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

抵扣说明:

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

余额充值