当前位置:网站首页>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
边栏推荐
猜你喜欢
![[pointer training - eight questions]](/img/fd/1aa3937548a04078c4d7e08198c3a8.png)
[pointer training - eight questions]

全国大学生信息安全赛创新实践赛初赛---misc(永恒的夜)

建模规范:命名规范

#PAT#day10

Communication between microservices

【Kubernetes 系列】一文學會Kubernetes Service安全的暴露應用

Is there a completely independent localization database technology

PMP practice once a day | don't get lost in the exam -7.5

JS regular filtering and adding image prefixes in rich text

Game theory matlab
随机推荐
Redis cluster deployment based on redis5
XSS challenges bypass the protection strategy for XSS injection
Is there a completely independent localization database technology
Detailed use of dbutils # yyds dry goods inventory #
codeforces每日5题(均1700)-第六天
NR modulation 1
07 singleton mode
BUUCTF刷题笔记——[极客大挑战 2019]EasySQL 1
2022工作中遇到的问题四
Briefly describe the implementation principle of redis cluster
Spherical lens and cylindrical lens
建模规范:命名规范
电机控制反Park变换和反Clarke变换公式推导
OCR文字識別方法綜述
【paddle】加载模型权重后预测报错AttributeError: ‘Model‘ object has no attribute ‘_place‘
Which ecology is better, such as Mi family, graffiti, hilink, zhiting, etc? Analysis of five mainstream smart brands
Descriptor implements ORM model
SD卡报错“error -110 whilst initialising SD card
Codeforces 5 questions par jour (1700 chacune) - jour 6
Overview of OCR character recognition methods