当前位置:网站首页>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
边栏推荐
猜你喜欢

【Kubernetes 系列】一文学会Kubernetes Service安全的暴露应用

codeforces每日5題(均1700)-第六天
![[matlab] access of variables and files](/img/cf/6f3cfdc4310fcf0bdcaa776d68261e.jpg)
[matlab] access of variables and files
![[network security interview question] - how to penetrate the test file directory through](/img/48/be645442c8ff4cc5417c115963b217.jpg)
[network security interview question] - how to penetrate the test file directory through

XSS challenges bypass the protection strategy for XSS injection

深入探究指针及指针类型

Gifcam v7.0 minimalist GIF animation recording tool Chinese single file version

Game theory matlab

Solve 9 with C language × 9 Sudoku (personal test available) (thinking analysis)

I sorted out a classic interview question for my job hopping friends
随机推荐
Communication between microservices
I sorted out a classic interview question for my job hopping friends
Buuctf question brushing notes - [geek challenge 2019] easysql 1
Codeforces 5 questions par jour (1700 chacune) - jour 6
Analyze 菜单分析
Jenkins basic knowledge ----- detailed explanation of 03pipeline code
MySQL advanced notes
主数据管理(MDM)的成熟度
【若依(ruoyi)】ztree 自定义图标(iconSkin 属性)
C语言sizeof和strlen的区别
Résumé des méthodes de reconnaissance des caractères ocr
电机控制反Park变换和反Clarke变换公式推导
2.13 simulation summary
Zhang Lijun: penetrating uncertainty depends on four "invariants"
Problems encountered in 2022 work IV
Introduction to robotframework (II) app startup of appui automation
How to improve the enthusiasm of consumers when the member points marketing system is operated?
CSP date calculation
【若依(ruoyi)】设置主题样式
【Kubernetes 系列】一文學會Kubernetes Service安全的暴露應用