ð 99. æ¢å€äºåæ玢æ
2022幎10æ10æ¥
- algorithm
ð 99. æ¢å€äºåæ玢æ
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode a = null;
TreeNode b = null;
TreeNode pre = null;
public void recoverTree(TreeNode root) {
// æè·¯ïŒ
// äžåºéå - äºåæ玢æ æåº
// éå°å䞪éåºçæ°ïŒè®°äžº a
// 继ç»åŸåéåïŒæŸå°éŠäžª ?.val > a.val
// ? åé¢çèç¹å°±æ¯ 第äºäžªæ°ïŒè®°äžº b
mySol(root);
if(a == null) {
a = root;
}
if(b == null) {
b = pre;
}
// System.out.println(a.val + " " + b.val);
int tmp = a.val;
a.val = b.val;
b.val = tmp;
}
private void mySol(TreeNode root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return;
}
if(a != null && b != null) {
return;
}
// root != null
mySol(root.left);
if(a != null && b != null) {
return;
}
// åå±éåœé»èŸ
TreeNode cur = root;
System.out.println(cur.val);
if(pre != null && cur.val < pre.val) {
// å€ææ¯ç¬¬äžäžªè¿æ¯ç¬¬äºäžª
if(a == null) {
a = pre;
} else {
b = cur;
return;
}
}
if(a != null && cur.val > a.val) {
b = pre;
return;
}
pre = cur;
mySol(root.right);
}
}