Problem:
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?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Solution:
Using Inorder Traverse.
Code
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode p;
TreeNode q;
TreeNode tmp = new TreeNode(Integer.MIN_VALUE);
public void recoverTree(TreeNode root) {
if (root == null) return;
recover(root);
if (p != null && q != null) {
int t = p.val;
p.val = q.val;
q.val = t;
}
}
public void recover(TreeNode root) {
if (root == null) return;
recover(root.left);
if (tmp != null && root.val < tmp.val) {
if(p == null) {
p = tmp;
q = root;
} else {
q = root;
}
}
tmp = root;
recover(root.right);
}
}