当前位置:网站首页>Leetcode problem solving -- 99 Restore binary search tree
Leetcode problem solving -- 99 Restore binary search tree
2022-07-06 03:07:00 【Snowy solitary boat】
public void recoverTree(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
TreeNode prev = null;
TreeNode node1=null,node2=null;
while (!stack.isEmpty()||node!=null){
while (node!=null){
stack.push(node);
node = node.left;
}
node = stack.pop();
if (prev!=null&&node.val<prev.val){
if (node1==null){
node1 = prev;
node2 = node;
}else {
node2 = node;
}
}
prev = node;
node = node.right;
}
if (node1!=null&&node2!=null){
int temp = node1.val;
node1.val = node2.val;
node2.val = temp;
}
}
Ideas :
The topic is about switching nodes , In fact, there are only two possibilities , The exchanged nodes are adjacent , Or the exchanged nodes are not adjacent
The exchanged nodes are adjacent :
ai and ai+1 In exchange for , Then there is ai>ai+1 Save two nodes
Can we exchange two nodes directly at this time ? Not at all , Because there is another situation
ai and aj In exchange for , After exchanging
ai>ai+1,aj-1>aj
These two cases are found at the first node , If the situation is the same, we can save the two nodes in the first case , Then, if the next unqualified point appears, it will ai+1 use aj Replace
Then the same switch two nodes at the end of the loop
边栏推荐
- 主数据管理理论与实践
- 1003 emergency (25 points), "DIJ deformation"
- Single instance mode of encapsulating PDO with PHP in spare time
- Introduction to robotframework (III) Baidu search of webui automation
- Inherit day01
- 这些不太会
- 【若依(ruoyi)】ztree 自定义图标(iconSkin 属性)
- Jenkins basic knowledge ----- detailed explanation of 03pipeline code
- I sorted out a classic interview question for my job hopping friends
- 【若依(ruoyi)】启用迷你导航栏
猜你喜欢

C language - Blue Bridge Cup - promised score

Apt installation ZABBIX

CobaltStrike-4.4-K8修改版安装使用教程

RobotFramework入门(一)简要介绍及使用

My C language learning record (blue bridge) -- on the pointer

Reverse repackaging of wechat applet

Microservice registration and discovery

Fault analysis | analysis of an example of MySQL running out of host memory

OCR文字识别方法综述

My C language learning records (blue bridge) -- files and file input and output
随机推荐
I sorted out a classic interview question for my job hopping friends
银行核心业务系统性能测试方法
07 单件(Singleton)模式
RobotFramework入门(三)WebUI自动化之百度搜索
Introduction to robotframework (II) app startup of appui automation
tcpdump: no suitable device found
[concept] Web basic concept cognition
Descriptor implements ORM model
codeforces每日5題(均1700)-第六天
What is the investment value of iFLYTEK, which does not make money?
[ruoyi] enable Mini navigation bar
Eight super classic pointer interview questions (3000 words in detail)
[ruoyi] set theme style
MySQL advanced notes
Inherit day01
有没有完全自主的国产化数据库技术
[Chongqing Guangdong education] higher mathematics I reference materials of Southwest Petroleum University
4. File modification
建模规范:命名规范
XSS challenges绕过防护策略进行 XSS 注入