Recover Binary Search Tree


Problem Statement :


You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.

Example 1:

Input: root = [1,3,null,null,2]
Output: [3,1,null,null,2]
Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.


Example 2:


Output: [2,1,4,null,null,3]
Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.
 

Constraints:

The number of nodes in the tree is in the range [2, 1000].
-231 <= Node.val <= 231 - 1



Solution :



title-img


                            Solution in C :

struct TreeNode * inorder(struct TreeNode * root, struct TreeNode ** p1, struct TreeNode ** p2, int d);

void recoverTree(struct TreeNode* root){
    struct TreeNode * p1 = NULL;
    struct TreeNode * p2 = NULL;
    int l = 0, r = 1;
    inorder(root, &p1, &p2, 0);
    p1->val = p1->val + p2->val;
    p2->val = p1->val - p2->val;
    p1->val = p1->val - p2->val;
}

struct TreeNode * inorder(struct TreeNode * root, struct TreeNode ** p1, struct TreeNode ** p2, int d){
    if (root == NULL)
        return NULL;
    struct TreeNode * cur = NULL;
    cur = inorder(root->left, p1, p2, 0);
    if (cur != NULL){
        if (cur->val > root->val){
            if (*p1 == NULL){
                *p1 = cur;
                *p2 = root;
            }
            else
                *p2 = root;
        }
    }
    int in_left = 0;
    if (*p1 != NULL)
        in_left = 1;
    cur = inorder(root->right, p1, p2, 1);
    if (cur != NULL){
        if (root->val > cur->val){
            if (*p1 == NULL){
                *p1 = root;
                *p2 = cur;
            }
            if (in_left == 1)
                *p2 = cur;
            else
                *p1 = root;
        }
    }
    if (d == 0){
        while (root->right != NULL)
            root = root->right;
    }
    else{
        while (root->left != NULL)
            root = root->left;
    }
    return root;
}
                        


                        Solution in C++ :

class Solution {
public:
    TreeNode* first = NULL, *second = NULL;
    void inorder(TreeNode* root, TreeNode* &prev){
        if(!root) return;
        inorder(root->left, prev);
        if(root->val<prev->val){
            if(!first)
            {first = prev;second=root;}
            else second=root;
        }
        prev=root;
        inorder(root->right, prev);
    }
    void recoverTree(TreeNode* root) {
        TreeNode* prev=new TreeNode(INT_MIN);
        inorder(root, prev);
        if(first) swap(first->val, second->val);
    }
};
                    


                        Solution in Java :

class Solution {
    public void recoverTree(TreeNode root) {
        if(root == null) return;

        TreeNode curr = root;
        TreeNode num1 = null;
        TreeNode num2 = null;
        TreeNode prev =null;

        while(curr!=null){
            if(curr.left==null){

                if(prev!=null && prev.val>curr.val){
                    if(num1==null && num2==null){
                        num1 = prev;
                        num2 = curr;
                    }
                    else{
                        num2 = curr;
                    }
                }
                prev = curr;
                curr = curr.right;
            }
            else{
                TreeNode temp = curr.left;
                while(temp.right!=null && temp.right!=curr){
                    temp = temp.right;
                }
                if(temp.right==null){
                    temp.right = curr;
                    curr = curr.left;
                }
                else{

                    if(prev!=null && prev.val>curr.val){
                        if(num1==null && num2==null){
                            num1 = prev;
                            num2 = curr;
                        }
                        else{
                            num2 = curr;
                        }
                    }
                    prev = curr;
                    temp.right = null;
                    curr = curr.right;
                }
            }
        }
        int temp = num1.val;
        num1.val = num2.val;
        num2.val = temp;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def recoverTree(self, root: Optional[TreeNode]) -> None:
        
        prev, first, second = None, None, None

        def inorder(node):
            nonlocal prev, first, second

            if node.left:
                inorder(node.left)
            
            if prev and first is None and prev.val>node.val:
                first = prev
            if prev and first is not None and prev.val>node.val:
                second = node
            
            prev = node

            if node.right:
                inorder(node.right)
        
        inorder(root)
        tmp = first.val
        first.val = second.val
        second.val = tmp
                    


View More Similar Problems

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →