99. Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
This is a very important skill while traversing tree.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode prev = null;
TreeNode first = null;
TreeNode second = null;
public void recoverTree(TreeNode root) {
findSwap(root);
int tmp = first.val;
first.val = second.val;
second.val = tmp;
}
void findSwap(TreeNode root){
if(root == null) return;
findSwap(root.left);
if(prev != null){
if(first == null && prev.val > root.val){
first = prev;
}
if(first != null && prev.val > root.val){
second = root;
}
}
prev = root;
findSwap(root.right);
}
}