threaded binary tree
1 public class Solution { 2 public void recoverTree(TreeNode root) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 TreeNode f1 = null, f2 = null; 6 TreeNode current,pre, parent = null; 7 8 if(root == null) 9 return; 10 boolean found = false; 11 current = root; 12 while(current != null) 13 { 14 if(current.left == null) 15 { 16 if(parent != null && parent.val > current.val) 17 { 18 if(!found) 19 { 20 f1 = parent; 21 found = true; 22 } 23 f2 = current; 24 } 25 parent = current; 26 current = current.right; 27 } 28 else 29 { 30 /* Find the inorder predecessor of current */ 31 pre = current.left; 32 while(pre.right != null && pre.right != current) 33 pre = pre.right; 34 35 /* Make current as right child of its inorder predecessor */ 36 if(pre.right == null) 37 { 38 pre.right = current; 39 current = current.left; 40 } 41 42 /* Revert the changes made in if part to restore the original 43 tree i.e., fix the right child of predecssor */ 44 else 45 { 46 pre.right = null; 47 if(parent.val > current.val) 48 { 49 if(!found) 50 { 51 f1 = parent; 52 found = true; 53 } 54 f2 = current; 55 } 56 parent = current; 57 current = current.right; 58 } /* End of if condition pre->right == NULL */ 59 } /* End of if condition current->left == NULL*/ 60 } /* End of while */ 61 62 if(f1 != null && f2 != null){ 63 int tmp = f1.val; 64 f1.val = f2.val; 65 f2.val = tmp; 66 } 67 68 } 69 }