LeetCode – Recover Binary Search Tree (Java)

Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure.

Java Solution

Inorder traveral will return values in an increasing order. So if an element is less than its previous element,the previous element is a swapped node.

public class Solution {
    TreeNode first;
    TreeNode second; 
    TreeNode pre; 
 
    public void inorder(TreeNode root){
        if(root==null)
            return;
 
        inorder(root.left);
 
        if(pre==null){
            pre=root;
        }else{
            if(root.val<pre.val){
                if(first==null){
                    first=pre;
                }
 
                second=root;
            }
            pre=root;
        }
 
        inorder(root.right);
    }
 
    public void recoverTree(TreeNode root) {
        if(root==null)
            return;
 
        inorder(root);
        if(second!=null && first !=null){
            int val = second.val;
            second.val = first.val;
            first.val = val;
        }
 
    }
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Govardhan

    Can someone explain this IF condition?

    if(first==null){
    first=pre;
    }

  • sorted array 1,2,3,4,5,6 => after a replacement => 1,5,3,4,2,6 or 1,3,2,4,5,6
    first occurance of issue (currentNode.val < prev.val ) and then first!=null then first=prev and do always second=currentNode [captures 2nd case/example of swapping]

    second occurance of issue (currentNode.val < prev.val ) then second = currentNode [captures 1st case/example]