Leetcode---Recover Binary Search Tree

leetcode之recover-binary-search-tree(搜索二叉树BST重建) leetcode之recover-binary-search-tree(搜索二叉树BST重建) 题目 Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n ) spac... 阅读详情

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Note:
A solution using O( n) space is pretty straight forward. Could you devise a constant space solution?


confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


Show Tags
Have you met this question in a real interview?

二叉排序树,中序遍历的时候应该输出一个有序序列。但是当反转的时候,就会出现当前节点小于前一节点的情况。记录第一个反转的节点和最后一个反转的节点,然后简单的互换节点内容即可,而无需互换节点本身。


  1. TreeNode * pre=NULL;
  2. TreeNode * p1=NULL;
  3. TreeNode * p2=NULL;
  4. void recoverTreeHelper(TreeNode *root) {
  5.     if(root==NULL)
  6.         return;
  7.     recoverTreeHelper(root->left);
  8.     if(pre==NULL)
  9.         pre=root;
  10.     else{
  11.         if(root->val<pre->val){
  12.             if(p1==NULL)
  13.                 p1=pre;
  14.             p2=root;
  15.         }
  16.         pre=root;
  17.     }
  18.     recoverTreeHelper(root->right);
  19. }
  20. void recoverTree(TreeNode *root) {
  21.     recoverTreeHelper(root);
  22.     if(p1!=NULL && p2!=NULL)
  23.         swap(p1->val,p2->val);
  24. }





<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(41) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
【LeetCode】Recover Binary Search Tree 解题报告 【题目】 Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could 阅读详情

相关推荐

转录组分析中的Fastp和FastQC:如何快速检测数据质量并优化流程

本文深入探讨了转录组分析中数据质量控制的核心流程,重点介绍了Fastp和FastQC两款工具的组合应用。FastQC负责对原始测序数据进行全面质量评估,生成可视化报告;Fastp则能一站式完成接头切除、低质量序列过滤、长度筛选等关键质控步骤。文章提供了详细的参数解读、实战脚本和自动化流程构建指南,帮助研究人员快速检测数据质量并优化预处理流程,为下游的差异表达等分析奠定可靠基础。

weixin_28452161的博客 181

leetcode 99. Recover Binary Search Tree

复习数据结构:二叉查找树 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public cl

独钓寒江雪 343

华为铁三角(AR、SR、FR)的考核指标设计

以和为核心,通过和实现协同。考核维度分为和,并随市场阶段动态调整权重。

从技术实践立足,从项目管理方法论延伸思考 2769

【Leetcode】Recover Binary Search Tree

题目链接:https://leetcode.com/problems/recover-binary-search-tree/ 题目: Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:

业精于勤,荒于嬉 3329

TensorRT-LLM环境配置避坑指南:从安装到实战

本文是一份详尽的TensorRT-LLM环境配置避坑指南。文章重点解析了从Python、CUDA、PyTorch版本选择,到解决mpi4py安装这一核心难题的完整流程,并提供了经过验证的稳定版本组合与实战排错方案,帮助开发者高效部署大语言模型推理优化环境。

a0b1c2d3的专栏 983

瑞萨MCU定时器API实战:从Smart Configurator配置到中断与输入捕获应用

在嵌入式系统开发中,定时器(Timer)是实现精准时序控制、PWM输出和信号测量的核心硬件外设。其工作原理基于计数器在稳定时钟源驱动下递增或递减,达到预设值后触发中断或改变输出电平,从而为系统提供节拍和事件基准。通过图形化配置工具(如瑞萨的Smart Configurator),开发者可以高效地将复杂的硬件寄存器操作转化为清晰、标准化的C语言API函数,这极大地提升了开发效率并降低了出错风险。这种从硬件抽象到软件接口的技术价值在于,它使得开发者能更专注于应用逻辑,而非底层细节,尤其适用于工业控制、汽车电子等

weixin_42519733的博客 274

LeetCode99—Recover Binary Search Tree

LeetCode99—Recover Binary Search Tree 恢复排序二叉树

上善若水 1586

Android客户端如何设计架构

当我们在新开发一款APP时,我们在初期要如何设计架构呢?在这里我根据我的经验,总结了一些基本的架构思路。 客户端架构设计的时候,首先需要充分考虑到所开发的app的类型,这里我分为功能型和服务型两大类,功能型的app侧重业务和功能,服务型的app侧重服务和运算。下面我就具体来讲讲针对这两种类型的通用架构。 功能型app 功能型app的activity比较多,整个app都以一个个activity承载业务和功能,在设计这类app时,我们需要考虑哪些要素呢? 由于activity比较多,我们需要考虑页面的跳转路由,

子者不语的专栏 1544

LeetCode力扣之99. Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing its structure.Note:A solution using O(n) space is pretty straight forward. Could you devise a consta...

LeeWei 316

微信小程序 - 实现Java微信支付退款功能以及退款流程,微信小程序前端+java后端完整示例源码,微信小程序退款功能详解,小程序订单申请退款和退款回调方法、查询退款等(新版微信支付,详细示例代码)

微信小程序开发-微信支付退款功能以及退款回调方法,微信支付退款API详解,微信小程序支付V3(支付、退款)Java实现微信小程序开发 小程序支付开发-小程序退款功能,微信小程序小程序和公众号 退款功能教程(含申请退款和退款回调,退款回调地址在商户后台配置或者代码自定义)最新版微信小程序支付,退款问题,小程序支付和退款功能详解,小程序申请退款,小程序处理退款,微信小程序支付与退款java,微信小程序退款及回调,JAVA实现微信小程序支付退款功能,退款api调用报错,如何解决退款申请无响应,如何用实现小程序订单

🏆 前端领域优质创作者 4159

AUTOSAR从入门到精通-【应用实战篇】车载HMI-ADAS

ADAS是高级驾驶辅助系统(Advanced Driving Assistance System)简称ADAS。ADAS高级驾驶辅助系统是利用安装于车上的各式各样的传感器, 在第一时间收集车内外的环境数据, 进行静、动态物体的辨识、侦测与追踪等技术上的处理, 从而能够让驾驶者在最快的时间察觉可能发生的危险, 以引起注意和提高安全性的主动安全技术。

lin_xiu的博客 1435

LeetCode Recover Binary Search Tree

LeetCode Recover Binary Search Tree 解题报告 二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。 最简单的办法,中序遍历二叉树生成序列,然后对序列中排序错误的进行调整。最后再进行一次赋值操作。

算法的天空 1万+

自定义载板RK3588HDMI输入配置完整解决方案

✅ HDMI输入信号检测✅ 自动时序识别(支持1080p@60Hz等标准格式)✅ V4L2视频设备接口✅ 实时视频流捕获✅ H.264编码录制✅ HDCP内容保护支持问题根因识别:发现了hdmim1模块资源冲突的本质问题硬件设计理解:明确了Orange Pi 5 Plus的真实硬件设计意图功能实现:成功启用HDMI输入功能,替代了无法使用的HDMI1输出完整验证:建立了从硬件检测到视频录制的完整测试流程。

梁俊星的博客 1271

【LeetCode】99.Recover Binary Search Tree(Hard)解题报告

【LeetCode】99.Recover Binary Search Tree(Hard)解题报告题目地址:https://leetcode.com/problems/recover-binary-search-tree/description/ 题目描述:   Two elements of a binary search tree (BST) are swapped by mistake.

郝春雨的博客 250

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

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

[leetcode] 99. Recover Binary Search Tree

Description Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Example 1: Input: [1,3,null,null,2] 1 / 3 \ 2 Output: [3,1...

Learning from the mistakes 318

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

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

【LeetCode】Recover Binary Search Tree

Recover Binary Search Tree  Total Accepted: 7163 Total Submissions: 31922 My Submissions Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its str

wangzq的专栏 1236

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

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

leetcode Recover Binary Search Tree

看到很多写Recover Binary Search Tree这道题的文章都用中序递归来做,我在这里告诉大家,这样做的空间复杂度也是O(n)的,所以虽然他们的答案虽然通过了,但还是没有符合题目的要求,O(1)空间复杂度遍历二叉树的一种算法是morris遍历,详见这里 以下为python的代码 class Solution: def __init__(self): #

大干的学习笔记 1095

LeetCode(99)Recover Binary Search Tree

题目如下: Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could yo

BUILD 1382

leetcode笔记:Recover Binary Search Tree

题目的大意是,在二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。

liyuefeilong的专栏 1591

LeetCode 之 Recover Binary Search Tree

原题: Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could

zhao123h的专栏 764

[LeetCode]Recover Binary Search Tree

原题链接 一题一句: BST 的内在性质,inorder traversal 里遵循的左小右大关系是突破口,俩个node错位最多只会导致出现俩次左大右小,只需交换第一次的前一个和第二次的后一个,若只有一次错位,则很简单。 经典题目补充:简而言之,java 传参传入的是指针,一担指针地址在方程内被改写,指针便与原来的地址失去关联。 这个题目有一点很有启发性,尤其对

Three_Thousand_World的博客 326

leetcode 99 Recover Binary Search Tree (python)

leetcode 99   Recover Binary Search Tree python

快递小可的博客 1175
上一篇: Leetcode---Flatten Binary Tree to Linked List
下一篇: Leetcode---Validate Binary Search Tree
我把葡萄酿成酒
博客等级 码龄12年 275粉丝 198原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值