当前位置:网站首页>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
边栏推荐
- Solution: attributeerror: 'STR' object has no attribute 'decode‘
- 【若依(ruoyi)】启用迷你导航栏
- Gifcam v7.0 minimalist GIF animation recording tool Chinese single file version
- CobaltStrike-4.4-K8修改版安装使用教程
- My C language learning records (blue bridge) -- files and file input and output
- Analyze menu analysis
- Pat 1046 shortest distance (20 points) simulation
- Audio audiorecord binder communication mechanism
- Mysql database operation
- C language - Blue Bridge Cup - promised score
猜你喜欢
随机推荐
Briefly describe the implementation principle of redis cluster
2022工作中遇到的问题四
Apt installation ZABBIX
A copy can also produce flowers
Some problem records of AGP gradle
Redis cluster deployment based on redis5
Web security SQL injection vulnerability (1)
What is the investment value of iFLYTEK, which does not make money?
Audio-AudioRecord Binder通信机制
The difference between sizeof and strlen in C language
Introduction to robotframework (III) Baidu search of webui automation
PMP每日一练 | 考试不迷路-7.5
codeforces每日5題(均1700)-第六天
Solution: attributeerror: 'STR' object has no attribute 'decode‘
My C language learning record (blue bridge) -- on the pointer
Maturity of master data management (MDM)
Analyze menu analysis
[ruoyi] ztree custom icon (iconskin attribute)
Misc (eternal night), the preliminary competition of the innovation practice competition of the National College Students' information security competition
Descriptor implements ORM model