226. Invert Binary Tree

SqlSugar避坑指南:C#操作MySQL时你可能会忽略的5个细节 本文分享了使用C#和SqlSugar框架操作MySQL数据库时的实战避坑指南。针对连接配置、实体映射、查询性能、事务处理等关键环节,深入剖析了5个容易被忽略但至关重要的细节,帮助开发者提升项目稳定性和执行效率,避免常见陷阱。 阅读详情

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1

这道题的就是我们常见的求二叉树的镜像,对于二叉树这种问题,第一直觉还是递归。

1.递归(DFS)

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == NULL)
            return NULL;

        invert_tree_detail(root);
        return root;
    }
private:
    void invert_tree_detail(TreeNode*& t){
        if(t->left == NULL && t->right == NULL)
            return ;
        if(t->left != NULL)
            invert_tree_detail(t->left);    //第一次在这里错写成了t=t->left,我还纳闷为什么没改变,唉~
        if(t->right != NULL)
            invert_tree_detail(t->right);
        std::swap(t->left, t->right);
    }
};



2.非递归,我当时想到了二叉树后序遍历,这个方法确实可以实现,但是较为复杂,其实呢它就是上面版本的非递归实现。(DFS)

利用一个对组,保存是从左右子树哪个回退的标记。

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == NULL)
            return NULL;

        invert_tree_detail(root);
        return root;
    }
private:
    typedef enum {L, R}FLAG;
    void invert_tree_detail(TreeNode*& t){
        std::pair<TreeNode*, FLAG> pr(t, L);
        std::stack<pair<TreeNode*, FLAG> > st;
        st.push(pr);
        
        do{
            TreeNode* tmp = st.top().first; 
            FLAG flag = st.top().second;
            st.pop();
            
            if(flag == L){
                st.push(std::make_pair(tmp, R));
                
                if(tmp->right != NULL)
                    st.push(std::make_pair(tmp->right, L));
                if(tmp->left != NULL)
                    st.push(std::make_pair(tmp->left, L));
            }
            else{
                std::swap(tmp->left, tmp->right);
            }
        }while(!st.empty());
    }
};


3.别人的递归方法,比我的简练,它是直接以第三方交换的方式递归,真的很不错(DFS)

class Solution {
    public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == NULL)
            return root;
        TreeNode* tmp = root->left;
        root->left = invertTree(root->right);
        root->right = invertTree(tmp);
        return root;
    }
};

4.迭代法

这个方法我绝壁没有想到,我只是想先深入下去交换最底层的子树,然后由下至上。而这个是迭代法,利用stack进行回溯。

class Solution {
    public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == NULL)
            return root;
        
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty()){
            TreeNode* tmp = st.top();
            st.pop();
            if(tmp != NULL){
                st.push(tmp->left);
                st.push(tmp->right);
                std::swap(tmp->left, tmp->right);
            }
        }
        return root;
    }
};


5.无意间看别别人解法的标题写了个BFS,我顿然醒悟这道题不仅有DFS,迭代,而且还有BFS。自己没有参考直接实现,一次性OJ。

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == NULL)
            return NULL;
        
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()){
            TreeNode* iter = que.front();
            que.pop();
            
            std::swap(iter->left, iter->right);
            
            if(iter->left != NULL)
                que.push(iter->left);
            if(iter->right != NULL)
                que.push(iter->right);
        }
        return root;
    }
};







Windows 10 下 Nacos 3.0.2 单机版保姆级安装教程(含JDK 17配置与MySQL 8.0连接避坑) 本文提供Windows 10下Nacos 3.0.2单机版的详细安装教程,涵盖JDK 17配置、MySQL 8.0连接优化及生产级安全设置。通过步骤详解和常见问题解决方案,帮助开发者快速完成Nacos的安装与配置,确保服务发现与配置管理的高效运行。 阅读详情

相关推荐

红外小目标检测新思路:当DETR遇上Mamba状态空间模型,速度提升3倍

本文探讨了将Mamba状态空间模型与DETR框架结合,用于解决红外小目标检测的难题。该创新方案通过线性复杂度的Mamba模块替代传统Transformer的自注意力机制,在保持高检测精度的同时,显著提升了推理速度,实现了实时性能的突破,为无人机巡检、安防监控等场景提供了高效解决方案。

hhh00的博客 666

LeetCode 226. Invert Binary Tree(二叉树)

题目来源:https://leetcode.com/problems/invert-binary-tree/ 问题描述 226.Invert Binary Tree Easy Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: ...

da_kao_la的博客 201

Xlinx PG151 除法器IP 笔记

对Xlinx 除法器IP PG151中部分内容记录备忘。

weixin_50515160的博客 2528

LeetCode 226 Invert Binary Tree题解

题目地址:https://leetcode.com/problems/invert-binary-tree/ 题目: Invert a binary tree. 反转一颗二叉树 4 / \ 2 7 / \ / \ 1 3 6 9 to 至 4 / \ 7 2 / \ / \ 9 6

赞美月亮的专栏 793

StarCCM+ 导入STL几何模型进行仿真

通过 Import Surface Mesh 的方法导入 STL 文件进行仿真

薛定谔的alpha狗 6131

图像质量评估(5) -- 畸变(Distortion)

当图像中原本应该是直线的地方看起来发生了不自然的变形或扭曲时,我们称为图像畸变。有三种类型的镜头畸变:桶形畸变(后文使用英文barrel),枕形畸变(后文使用pincushion)和胡子畸变(后文使用英文wavef或mustache,这种畸变里包含了桶形畸变和枕形畸变)。有一个重要的点需要注意,根据透镜的类型以及透镜是否能够从相机中移除等条件不同,畸变会有不同的表现。 总的来说,旋转对称光学系统功能上会产生和物体几何相似的图形。但也有少数特殊的系统是例外,例如鱼眼镜头,这种镜头几何是故意设计为

vivo01的专栏 2万+

Leetcode-226. Invert Binary Tree

Leetcode-226. Invert Binary Tree

Eistert 149

Labview_DQMH框架学习1--浅析

本文主要结合一个相对容易理解的例子,阐述 DQMH 框架的工作原理,希望对初学者有一定的帮助。

hrbeuxn的博客 3054

leetcode 226: Invert Binary Tree

leetcode 226: Invert Binary Tree python java c++

西施豆腐渣 5328

【软件系统架构】系列四:嵌入式软件-NPU(神经网络处理器)系统及模板

NPU(Neural Processing Unit) 是专门用于人工神经网络推理与训练的处理器,具备高并行、低功耗、低延迟等特点。它是边缘 AI、自动驾驶、智能摄像头、语音识别等场景中的关键硬件。

moton2017的博客 2256

uniapp | vue2 | vue3 - 解决调用天地图功能服务时 http 网络请求报错 net::ERR ABORTED 503(Service Temporarily Unavailabl)

vue,uni-app,天地图,请求报错,503,请求失败,map.tianditu,天地图503,天地图请求503,接口503错误怎么办,vue天地图,uniAPP天地图,获取定位接口服务器报错503,获取当前定位,定位功能,IP属地定位,天地图服务器报错,如何解决报错,net::ERRABORTED503(ServiceTemporarilyUnavailabl),GET,POST,服务暂时不可用,react天地图,一直等待吗,报错怎么办,定位报错,轨迹,经纬度,天地图服务器503,在vue2

🏆 前端领域优质创作者 4440

226. Invert Binary Tree [easy] (Python)

题目链接https://leetcode.com/problems/invert-binary-tree/题目原文 Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: Thi

Coder_Orz的博客 4940

如何正确的计算两个角度的角度差?

这一步是必要的,因为它确保了无论a相对于b是在逆时针方向还是顺时针方向,d2总是正确地反映出绕圆相反方向的角度差。这样,当函数进行最后的比较时,它能够准确地比较两个方向的旋转路径并选择最短的一个。

小秋 AI SLAM 入门实战教程 4141

Leetcode226 Invert Binary Tree

Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem was inspired by this original tweet by Max Howe

suichen1的专栏 498

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 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 226. Invert Binary Tree (python)

leetcode 226. Invert Binary Tree题目解法1:利用递归(recursive)形式1形式2(跟简洁,直接用原函数进行递归)解法2:利用迭代(iterative) 题目 Invert a binary tree.(具体题目参考leetcode官网) 解法1:利用递归(recursive) 递归的将每个节点的左右节点调换 形式1 class Solution(object)...

qq_37821701的博客 450

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Leetcode226. Invert Binary Tree

反转二叉树,将二叉树所有的节点的左右两个孩子交换。

magic_jiayu的博客 263

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

226Invert Binary Tree

Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem was inspired by this original tweet by Max Howe

littledouble的专栏 528

[226] Invert Binary Tree

Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1翻转一棵二叉树。EZ题。方法1:整体思路就是层次遍历,然后把左右孩子对调。 ...

diaofu3864的博客 111

Invert Binary Tree - LeetCode 226

题目描述: Invert a binary tree.      4    /   \   2     7  / \   / \ 1   3 6   9 to      4    /   \   7     2  / \   / \ 9   6 3   1 Trivia: This problem was inspired by this origi

bu_min的博客 548

LeetCode 226 Invert Binary Tree

题目 Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output:* 4 / \ 7 2 / \ / \ 9 6 3 1 解法思路(一) 反转一棵二叉树,就是将每个节点的左...

乌鲁木齐001号程序员 97

226. Invert Binary Tree的C++解法

考虑到要遍历整棵树,所以选了广度优先遍历的方法,把每个节点加入队列之后交换它的左右子树指针就好了。 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x)

MuseCP@YenTown 476
上一篇: 225. Implement Stack using Queues
下一篇: 90. Subsets II
FreeeLinux
博客等级 码龄11年 421粉丝 356原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值