99. 恢复二叉搜索树
二叉搜索树中的两个节点被错误地交换。
请在不改变其结构的情况下,恢复这棵树。
示例 1:
输入: [1,3,null,null,2]
1
/
3
\
2
输出: [3,1,null,null,2]
3
/
1
\
2
示例 2:
输入: [3,1,4,null,null,2]
3
/ \
1 4
/
2
输出: [2,1,4,null,null,3]
2
/ \
1 4
/
3
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private TreeNode pre = null;
private TreeNode mistake1,mistake2 = null;
public void recoverTree(TreeNode root) {
inOrderTraversal(root);
int temp = mistake2.val;
mistake2.val = mistake1.val;
mistake1.val = temp;
}
public void inOrderTraversal(TreeNode root){
if(root == null)
return;
inOrderTraversal(root.left);
if(pre != null && pre.val > root.val){
if(mistake1 == null)
mistake1 = pre;
mistake2 = root;
}
pre = root;
inOrderTraversal(root.right);
}
}