Fixing Two nodes of a BST | Practice | GeeksforGeeks

By swapping nodes 11 and 10, the BST 
can be fixed.


Your Task:
You don't need to take any input. Just complete the function correctBst() that takes root node as parameter. The function should not return anything, all the changes must be done in the existing tree only. BST will then be checked by driver code and 0 or 1 will be printed.

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ Number of nodes ≤ 103
0
gulshan996 days ago
class Solution {
  public:
    Node*first=NULL;
     Node*second=NULL;
      Node*prev = NULL;
      void help(Node*root){
          if(root==NULL)return;
          help(root->left);
          if(prev==NULL)prev = root;
          else{
              if(first == NULL and prev->data >= root->data)first=prev;
               if(first != NULL and prev->data >= root->data)second=root;
          }
          prev= root;
          help(root->right);
      }
    void correctBST( struct Node* root )
    {
        // add code here.
        help(root);
        swap(first->data , second->data);
    }
};

+2
adarshgupta4012 weeks ago
Easy n Simple Inorder Implementation-
Java-
class Solution
{
    private Node first;  private Node  middle; 
    private Node  last;  private  Node prev;   // prev var to store previous nod
    
     private void inorder(Node root){
        if(root == null) return;
        inorder(root.left);
        if(prev != null && ( root.data < prev.data ) )  // first voilation
        {
            if(first == null){ // if this is first voilation then change fisrt and middle 
                first  = prev;
                middle = root;
            }
            else { // if this is 2nd voilation then change last
                last = root;
            }
        }
        prev = root;
        inorder(root.right); 
    }
    
    //Function to fix a given BST where two nodes are swapped.  
    public Node correctBST(Node root)
    {
        Node dummy = root;
        first = middle = last = null;
        prev = new Node (Integer.MIN_VALUE);
        
        inorder(root);
        
        if(last != null){          // exchange first and last
            int temp = first.data;
            first.data = last.data;
            last.data = temp;
        }
        else{                      // exchange first and middle
            int temp = first.data;
            first.data = middle.data;
            middle.data = temp;
        }
        return dummy;
    }
}
0
amishasahu3282 weeks ago
class Solution {
    struct Node* prev, *first, *middle, *last;
  public:
    void inorder(struct Node *root)
    {
        if(!root) return;
        inorder(root->left);
        if(prev != NULL && root->data < prev->data)
        {
            if(!first)
            {
                first = prev;
                middle = root;
            }
            else
                last = root;
        }
        prev = root;
        inorder(root->right);
    }
    void correctBST( struct Node* root )
    {
        // add code here.
        first = middle = last = NULL;
        prev = new Node(INT_MIN);
        if(!root) return;
        inorder(root);
        if(first && last) swap(first->data, last->data);
        else if(first && middle) swap(first->data, middle->data);
    }
};
0
deskhell4 weeks ago
//T.C: O(n), S.C: O(1), using Morris Traversal.

class Solution {
  public:
    void correctBST( struct Node* root )
    {
        // add code here.
        
        Node* curr = root, *prev = NULL, *a = NULL, *b = NULL;
        while(curr){
            if(!curr -> left){
                if(prev and prev -> data > curr -> data){
                    if(!a)a = prev;
                
                    b = curr;
                }
                
                prev = curr;
                curr = curr -> right;
            }
            else{
                Node* rm = curr -> left;
                while(rm -> right and rm -> right != curr)rm = rm -> right;
                
                if(rm -> right == NULL){
                    rm -> right = curr;
                    curr = curr -> left;
                }
                else{
                    
                    if(prev -> data > curr -> data){
                        if(!a)a = prev;
                        b = curr;
                    }
                    
                    rm -> right = NULL;
                    prev = curr;
                    curr = curr -> right;
                }
            }
        }
        swap(a -> data, b -> data);
    }
};
+1
itsnaveen1 month ago
SIMPLE C++ solution with inorder traversal in O(N) time :
two pointers
 first and f: are first nodes where increasing order value is violated in inorder traversal.
last and l : are second time it happened.
Prev and p : are pointer that tracks node behind the ROOT in inorder traversal.
class Solution {
  public:
     void swap(int *a , int *b)
     {
         int temp = *a;
         *a=*b;
         *b=temp;
     }
  
    void help(Node *root, Node** f , Node** l , Node** p)
    {
        if(root==NULL)
            return ;
        
        help(root->left, f, l , p);
        
        if(*p and root->data <= (*p)->data )
        {
            if(!*f)
                *f=*p;
            
            *l=root;    
        }
        
        *p=root;
        
        help(root->right, f, l, p);
    }
    void correctBST( struct Node* root )
    {
        // add code here.
        Node* first=NULL;
        Node* last = NULL;
        Node* prev = NULL;
        
        help(root, &first ,& last , &prev);
        
        if(first&&last)
            swap(&(first->data),&(last->data));
    }
};
 
 
0
bhaskarmaheshwari81 month ago
 void inorder(Node *root) {     if(root==NULL)       return;              inorder(root->left);       if(prev!=NULL&&root->data<prev->data)       {           if(first==NULL)           {               first=prev;               middle=root;                          }           else           last=root;       }       prev=root;       inorder(root->right); }    void correctBST( struct Node* root )   {       // add code here.       inorder(root);       if(last)       swap(last->data,first->data);       else       swap(first->data,middle->data);          }
0
akashmr10961 month ago
O(1) Space
 
public Node correctBST(Node root)
    {
        Deque<Node> order = new LinkedList<>();
        Node[] error = new Node[2];
        error[0] = null;
        error[1] = null;
        inorder(root, order, error);
        int temp = error[0].data;
        error[0].data = error[1].data;
        error[1].data = temp;
        return root;
    }
    
    public static void inorder(Node root, Deque<Node> travel, Node[] error) {
        if (root == null) {
            return;
        }
        
        inorder(root.left, travel, error);
        
        if (error[0] == null && !travel.isEmpty() && travel.peekLast().data > root.data) { // this means previous node is corrupted and needs to be stored
            error[0] = travel.peekLast();
            error[1] = root;
        } else if (!travel.isEmpty() && travel.peekLast().data > root.data) { // this means current node is corrupted and needs to be stored
            error[1] = root;
        }
        travel.pollLast();
        travel.addLast(root);
        
        inorder(root.right, travel, error);
    }
0
sandeep55211 month ago
O(n) time and O(1) space C++ Solution by using Morris Traversal.
void correctBST( struct Node* root )
   {
       // add code here.
       Node *curr=root;
       Node *prev=NULL,*f=NULL,*s=NULL;
       while(curr)
       {
           if(!(curr->left)){
               if(prev and root->val< prev->val){
                   if(f){
                       swap(f->val,root->val);
                       f=NULL;
                   }
                   else{
                       f=prev;
                       s=root;
                   }
               } 
               prev=curr;
               curr=curr->right;
           }
           else{
               Node *ptr=curr->left;
               while(ptr->right and ptr->right!=curr)
                   ptr=ptr->right;
               if(!(ptr->right)){
                   ptr->right=curr;
                   curr=curr->left;
               }
               else{
                   ptr->right=NULL;
                   if(prev and root->val< prev->val){
                       if(f){
                           swap(f->val,root->val);
                           f=NULL;
                       }
                       else{
                           f=prev;
                           s=root;
                       }
                   } 
                   prev=curr;
                   curr=curr->right;
               }
           }
       }
       if(f) swap(f->val,s->val);
   }
0
hamidnourashraf2 months ago
WHAT IS WRONG WITH THIS CODE???????????


import math

#Function to fix a given BST where two nodes are swapped.  
class Solution:
    res = []
    def check_BST(self, root, min_val, max_val):
        if root is None:
            return 
        if root.data > max_val or root.data < min_val:
            self.res.append(root)
            return 
        self.check_BST(root.left, min_val, root.data-1)
        self.check_BST(root.right, root.data+1, max_val)
        
    def correctBST(self, root):
        self.check_BST(root, -math.inf, math.inf)
        if len(self.res) == 2:
            self.res[0].data , self.res[1].data = self.res[1].data , self.res[0].data
        elif len(self.res) == 1:
            self.res[0].data, root.data = root.data, self.res[0].data
It gives error on  93 61 87 9 but when I tested as custom input, it passes!!!!
 
 
0
007msr0072 months ago
C++ Using Inorder Traversal :
class Solution {
  public:
  void help(Node *root,Node *&first,Node *&second,Node *&prev)
  {
      if(root==NULL)
        return;
     help(root->left,first,second,prev);
     if(prev!=NULL && root->data<prev->data)
     {
         if(first==NULL)
          first = prev;
          second = root;
     }
     prev = root;
    help(root->right,first,second,prev); 
  }
    void correctBST( struct Node* root )
    {
        // add code here.
       Node *first = NULL ,*second =NULL,*prev=NULL;
       help(root,first,second,prev);
       int temp = first->data ;
       first->data = second->data;
       second->data = temp;
    }
};
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.