Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public void recoverTree(TreeNode root) { 3 if(root==null) return ; 4 ArrayList<TreeNode> t = new ArrayList<TreeNode> (); 5 ArrayList<Integer> v = new ArrayList<Integer> (); 6 get(root,t,v); 7 Collections.sort(v); 8 for(int i=0;i<v.size();i++){ 9 t.get(i).val = v.get(i); 10 } 11 } 12 public void get(TreeNode root,ArrayList<TreeNode> t,ArrayList<Integer> v){ 13 if(root==null) return ; 14 get(root.left,t,v); 15 t.add(root); 16 v.add(root.val); 17 get(root.right,t,v); 18 } 19 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public void recoverTree(TreeNode root) { 3 TreeNode cur,parent = null,pre,f1=null,f2=null; 4 boolean Found = false; 5 cur = root; 6 if(root==null) return ; 7 while(cur!=null){ 8 if(cur.left==null){ 9 if(parent!=null && parent.val> cur.val){ 10 if(!Found){ 11 Found=true; 12 f1 = parent; 13 } 14 f2 = cur; 15 } 16 parent = cur; 17 cur = cur.right; 18 } 19 else{ 20 /* Find the inorder predecessor of current */ 21 pre = cur.left; 22 while(pre.right!=null && pre.right!=cur){ 23 pre = pre.right; 24 } 25 /* Make current as right child of its inorder predecessor */ 26 if(pre.right==null){ 27 pre.right = cur; 28 cur = cur.left; 29 } 30 /* Revert the changes made in if part to restore the original 31 tree i.e., fix the right child of predecssor */ 32 else { 33 pre.right =null; 34 if(parent!=null && parent.val> cur.val){ 35 if(!Found){ 36 Found=true; 37 f1 = parent;//should not use else 38 } 39 f2 = cur; 40 } 41 parent = cur; 42 cur = cur.right; 43 } 44 } 45 } 46 if(f1!=null && f2!=null){ 47 int temp = f1.val; 48 f1.val = f2.val; 49 f2.val = temp; 50 } 51 } 52 }