Video není dostupné.
Omlouváme se.

L52. Recover BST | Correct BST with two nodes swapped

Sdílet
Vložit
  • čas přidán 5. 11. 2021
  • Entire DSA Course: takeuforward.org/strivers-a2z...
    Check our Website:
    Linkedin/Instagram/Telegram: linktr.ee/takeUforward
    #treeSeries #striver #placements

Komentáře • 121

  • @takeUforward
    @takeUforward  Před 2 lety +50

    Please like and share :)

  • @AdityaSharma-nr7qn
    @AdityaSharma-nr7qn Před 2 lety +69

    What a co incidence, I was exactly studying the same problem and wasn't able to understand on my own and here comes Striver for rescue 😀😀

  • @ajaykr2811
    @ajaykr2811 Před 11 měsíci +18

    instead of making third variable we can also update the middle variable when there is a 2nd violation

  • @jiteshsingh4899
    @jiteshsingh4899 Před 2 lety +13

    my mom said "ye ladka kitni mehnat karta h" - what a explanation striver bhaiya

  • @chitranshjain5075
    @chitranshjain5075 Před 2 lety +2

    Such a brilliant explanation of the problem! Thank you very much fir helping all of us!

  • @namratam1522
    @namratam1522 Před rokem +1

    You are the best instructor !! Thanks a ton for this content ! You are bringing a revolution striver!

  • @shinewanna3959
    @shinewanna3959 Před rokem +14

    As u initialize prev as INT_MIN then u don't need to check prev != null in inorder recursive. Just correction. You are already great.

    • @darkexodus6404
      @darkexodus6404 Před 11 měsíci +1

      In leetcode question the values are in range of [INT_MIN, INT_MAX], so this won't work there.

  • @Ramu9119
    @Ramu9119 Před 7 měsíci

    excellent explanation striver bhai

  • @stith_pragya
    @stith_pragya Před 8 měsíci +1

    Thank You So Much for this wonderful video...🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @tempbot7190
    @tempbot7190 Před měsícem

    Much Love from London❤

  • @dhrutidesai278
    @dhrutidesai278 Před 4 měsíci

    Thankyou sir👍For always helping by your approaches

  • @preetisahani5054
    @preetisahani5054 Před 10 měsíci

    Awesome explanation

  • @ujjwalverma5893
    @ujjwalverma5893 Před 2 lety +10

    We can avoid the middle pointer also just keep updating the first and second pointers -
    class Solution {
    private TreeNode first;
    private TreeNode second;
    private TreeNode prev;
    public void recoverTree(TreeNode root) {
    inorder(root);
    int temp = first.val;
    first.val = second.val;
    second.val = temp;
    }
    public void inorder(TreeNode root) {
    if(root == null) return;
    inorder(root.left);
    // Keep updating first and second which points to first and second numbers to swap
    if(prev != null && root.val < prev.val) {
    if(first == null) {
    first = prev;
    second = root;
    } else {
    second = root;
    }
    }
    prev = root;
    inorder(root.right);
    }
    }

  • @timjoyalle318
    @timjoyalle318 Před 2 lety +3

    This dude's neighbors get free lectures. Hope they appreciate it.

  • @shashankbajpai5659
    @shashankbajpai5659 Před 2 lety +6

    add morris traversal and we can do this problem on O(1) space as well.

  • @krishnaradhey2814
    @krishnaradhey2814 Před rokem +4

    LeetCode 99 problem Can be done with morris traversal

  • @amanbhadani8840
    @amanbhadani8840 Před 2 lety +3

    Absolutely brilliant explanation as well as mind blowing implementation of code,just loved it bhaiya.

  • @ZebraZodiac
    @ZebraZodiac Před 2 měsíci +1

    If trying to code in python use list to store prev,first,last and middle (or prev and last if not using middle) as when prev is just declared as just an argument, it gets reassigned and will not get passed on to the next recursive call.

  • @SatyamKumar-bw4vi
    @SatyamKumar-bw4vi Před rokem +4

    Hare Krishna..!
    Got Placed in R & D of a Product Based Company..!
    Thanks Bhaiya..!
    I will tag you in Linkedln post in some time

  • @jerrywong5140
    @jerrywong5140 Před 2 lety +2

    Very helpful and thorough explanation, love it!

  • @SharuxD
    @SharuxD Před rokem +1

    The logic you have given to solve this is brilliant af. GG

  • @pratikmhatre4815
    @pratikmhatre4815 Před rokem +5

    I always feel motivated by your passion of explaining problems👍

  • @adebisisheriff159
    @adebisisheriff159 Před 6 měsíci

    Thanks Man!!!

  • @kalpeshmali1476
    @kalpeshmali1476 Před 2 lety +3

    After watching your tree series i m pretty confident in Binary trees and bst 🔥🔥🔥🔥🔥🔥🔥

  • @Mathurfrombihar
    @Mathurfrombihar Před 2 lety +3

    //first brute method
    vectorv;
    int i=0;
    void tra(Node *root)
    {
    if(!root) return;
    tra(root->left);
    v.push_back(root->data);
    tra(root->right);
    }
    void check(Node *root)
    {
    if(!root) return;
    check(root->left);
    if(v[i]!=root->data)
    {
    swap(root->data,v[i]);
    }
    i++;
    check(root->right);
    }
    void correctBST( struct Node* root )
    {
    tra(root);
    sort(v.begin(),v.end());
    check(root);
    }

  • @user-tk2vg5jt3l
    @user-tk2vg5jt3l Před 4 měsíci

    Thank you Bhaiya

  • @studyafa7159
    @studyafa7159 Před 5 měsíci +1

    i think there is no need of " prev != null" in line 27

  • @philipbrujic4728
    @philipbrujic4728 Před 2 dny

    good video

  • @anubhavpabby6856
    @anubhavpabby6856 Před 2 lety +8

    Thank you striver bhaiya for making such a great series and it's helping me out in placement preparation

    • @parthsalat
      @parthsalat Před rokem +2

      You seem to like teddy bears a lot

  • @gandhijainamgunvantkumar6783

    Thank you so much striver bhaiya for providing such an amazing content :)

  • @ayushbhargava8400
    @ayushbhargava8400 Před 6 měsíci

    find the two elements which are not at it's correct place through inorder traversal vector and sorted vector. again perform inorder traversal and have a check on root element if it's equal to incorrect element swap it.

  • @DeependraSingh-jh8xf
    @DeependraSingh-jh8xf Před 10 měsíci

    fire hai bhau

  • @shagunlamba6481
    @shagunlamba6481 Před 2 lety +2

    Great explanation , thank you.

  • @ishakhutafale1163
    @ishakhutafale1163 Před měsícem

    Watch these videos, and you'll never forget the importance of inorder traversal for BSTs!

  • @aakashgoswami2356
    @aakashgoswami2356 Před 2 lety +15

    Brute force Code:
    class Solution {
    public:
    void inorderTraversal(TreeNode* root,vector&arr){

    if(root==NULL)
    return;

    inorderTraversal(root->left,arr);
    arr.push_back(root->val);
    inorderTraversal(root->right,arr);
    }

    void recoverBST(TreeNode* root, vector&arr,int &i){
    if(root==NULL)
    return;

    recoverBST(root->left,arr,i);
    if(root->val != arr[i]){
    root->val = arr[i];
    }
    i++;
    recoverBST(root->right,arr,i);

    }

    void recoverTree(TreeNode* root) {
    vectorarr;
    inorderTraversal(root,arr);
    sort(arr.begin(),arr.end());
    // for(auto ar:arr)cout

    • @susantakumardutta6283
      @susantakumardutta6283 Před rokem +1

      We have to make variable i, a global variable. So, that it can get updated after every recursive call.

  • @harshitjaiswal9439
    @harshitjaiswal9439 Před 5 měsíci

    understood.

  • @abhinanda7049
    @abhinanda7049 Před 2 měsíci

    understood

  • @stith_pragya
    @stith_pragya Před 8 měsíci +4

    🚨[IMPROVMENT IN THE CODE]:🚨
    Hello Striver Bhaiya,
    1- if you would have done middle = root in the else part then you wouldnt have had any requirement of the variable "last", you can do it using only two variables.
    2- You could have also used an array of size 3 instead of global variables.
    But if your intention to was make code simpler for others to understand then it is all fine.....👍

    • @gyanendrasaurav877
      @gyanendrasaurav877 Před 6 měsíci +1

      i also solved it using two vaiables because if in first case we can find the prev value at which the root value is less than prev then that means we find the greater element so the next voilation is always less than the first voilation so we can store last as root

  • @prashantsahu6212
    @prashantsahu6212 Před 2 lety +2

    Just wow, the intution was awesome.

  • @vinaygoswami5374
    @vinaygoswami5374 Před 2 lety

    Quite ambiguous explanation.

  • @shantanukumar4081
    @shantanukumar4081 Před 2 lety +1

    Great Explanation !!!

  • @niranjansaha5135
    @niranjansaha5135 Před rokem +1

    the first method can be optimised to O(n) + O(n) time, by removing the redundant sorting,
    void dfs(Node* root, vector &inorder){
    if(root == NULL) return;
    dfs(root->left, inorder);
    inorder.push_back(root);
    dfs(root->right, inorder);
    }
    void correctBST( struct Node* root )
    {
    vector inorder;
    dfs(root, inorder);
    int ct = 0;
    vector pos;
    for(int i = 1; i < inorder.size(); i++){
    if(inorder[i]->data < inorder[i-1]->data){
    pos.push_back(i);
    ct++;
    }
    }
    if(ct == 1){
    swap(inorder[pos[0] - 1]->data, inorder[pos[0]]->data);
    }
    else if(ct == 2){
    swap(inorder[pos[0]-1]->data, inorder[pos[1]]->data);
    }
    }

  • @tusharagarwal5306
    @tusharagarwal5306 Před 4 měsíci +1

    13:55 which online coding judge or editor is that??

  • @sparshsharma6068
    @sparshsharma6068 Před 2 lety +1

    Amazing explanation bhaiya!

  • @prasadm3614
    @prasadm3614 Před rokem

    Congratulations on 3 Lakh Subscribers

  • @peddikarthik7832
    @peddikarthik7832 Před rokem

    even if we keep all variables and functions of class in public, code still works. But why are we keeping private for some functions and variables ?

  • @adiin-1940
    @adiin-1940 Před rokem +1

    Shouldn't line number 24 of C++ be , if(prev ->Val != INT_MIN &&.....) rather than if(prev!=NULL &&....) because prev has already been set to a TreeNode with a value of INT_MIN so it will never be NULL?

    • @mayankbharti531
      @mayankbharti531 Před rokem +1

      just using "if(root->val < prev->val)" is fine as the first root->val will always be greater than the INT_MIN so it automatically won't check for the first node.

  • @muditkhanna8164
    @muditkhanna8164 Před 11 měsíci

    but what if there are more than one nodes that are swapped?

  • @shivambajpeyi9008
    @shivambajpeyi9008 Před 2 lety

    this was smooth!

  • @sreekanthyadav5801
    @sreekanthyadav5801 Před měsícem

    For many problems in BST,
    MORRIS Inorder approach is giving Stack Overflow error (RUN TIME ERROR).
    Is it same with everybody ?

  • @papayasprout
    @papayasprout Před 2 lety

    Thanks for the video man.

  • @ErfanHossainShoaib
    @ErfanHossainShoaib Před rokem

    If the inorder sequence is 3 25 7 8 10 15 20 12. Then...

  • @JujareVinayak
    @JujareVinayak Před rokem

    Which device is used in videos?? I need one to practice.

  • @anumoynandy5811
    @anumoynandy5811 Před rokem +4

    Check out Morris Inorder traversal code related to these problem
    class Solution {
    public:
    void recoverTree(TreeNode* root) {

    if(!root){
    return;
    }

    TreeNode*cand1=NULL;

    TreeNode*cand2=NULL;

    TreeNode*prev=NULL;

    TreeNode*curr=root;

    while(curr){

    if(curr->left==NULL){

    if(prev){

    if(prev->val > curr->val){

    if(cand1==NULL){
    cand1=prev;
    }

    cand2=curr;

    }

    }

    prev=curr;

    curr=curr->right;

    }

    else{

    TreeNode*temp=curr->left;

    while(temp && temp->right && temp->right!=curr){
    temp=temp->right;

    }

    if(temp->right==NULL){

    temp->right=curr;

    curr=curr->left;

    }

    else{

    if(prev){
    if(prev->val > curr->val){
    if(cand1==NULL){
    cand1=prev;
    }
    cand2=curr;
    }
    }
    prev=curr;

    temp->right=NULL;

    curr=curr->right;

    }

    }

    }

    swap(cand1->val,cand2->val);

    }
    };

  • @keshavagrawal1027
    @keshavagrawal1027 Před 2 měsíci

    can someone tell me why in the last we do (prev=root ) pls if u know try to give a explanation...🙏

  • @lavanyaprakashjampana933

    we love your content and we love you......🤟🖤

  • @silicon9794
    @silicon9794 Před rokem

    Perfectly explained....

  • @siddhaarthsingh7414
    @siddhaarthsingh7414 Před 2 lety +1

    Why prev = new Tree(INT_MIN)
    That is not required !!!!
    Pls Anyone ???

    • @arpitjaswal4210
      @arpitjaswal4210 Před 2 lety

      I simply made the prev node NULL and the code still got accepted.

  • @jagjiwanchimkar8106
    @jagjiwanchimkar8106 Před 2 lety +1

    When this Series Complete

  • @16aniketdutta58
    @16aniketdutta58 Před 2 lety +1

    The middle pointer can be avoided I guess!!!

    • @placementbaadshah8604
      @placementbaadshah8604 Před 2 lety

      czcams.com/video/k2haMtP7nvs/video.html

    • @your_name96
      @your_name96 Před 2 lety

      yup,
      class Solution {
      TreeNode *prev;
      TreeNode *first;
      // TreeNode *middle;
      TreeNode *last;
      public:
      void inorder(TreeNode* root){
      if(!root)return;
      inorder(root->left);
      // the node is not the root element
      if(prev != NULL and (root->val < prev->val)){
      // if this is the first element
      if(first == NULL){
      first = prev;
      }
      last = root;
      }
      prev = root;
      inorder(root->right);
      }
      void recoverTree(TreeNode* root) {
      prev = first = last = NULL;
      inorder(root);

      swap(first->val,last->val);

      }
      };

  • @spyrowolf2211
    @spyrowolf2211 Před 2 lety +2

    what drawing software are u using?

  • @justinmyth4980
    @justinmyth4980 Před 2 lety

    Why you have used middle,we can just update last instead of middle and it works fine??

    • @placementbaadshah8604
      @placementbaadshah8604 Před 2 lety

      czcams.com/video/k2haMtP7nvs/video.html

    • @your_name96
      @your_name96 Před 2 lety

      I guess it works for understanding the algorithm then optimising it to first and last become easier
      class Solution {
      TreeNode *prev;
      TreeNode *first;
      // TreeNode *middle;
      TreeNode *last;
      public:
      void inorder(TreeNode* root){
      if(!root)return;
      inorder(root->left);
      // the node is not the root element
      if(prev != NULL and (root->val < prev->val)){
      // if this is the first element
      if(first == NULL){
      first = prev;
      }
      last = root;
      }
      prev = root;
      inorder(root->right);
      }
      void recoverTree(TreeNode* root) {
      prev = first = last = NULL;
      inorder(root);

      swap(first->val,last->val);

      }
      };

    • @justinmyth4980
      @justinmyth4980 Před 2 lety

      @@your_name96 thanks bro btw which are u a college student?

    • @mohit9975
      @mohit9975 Před rokem +1

      @@justinmyth4980 Islamabad university , lahore

  • @jsuryakt
    @jsuryakt Před 2 lety +4

    class Solution {
    TreeNode prev;
    TreeNode violation1;
    TreeNode violation2;

    public void inorder(TreeNode root) {
    if(root == null)
    return;

    inorder(root.left);

    if(prev != null && prev.val > root.val)
    {
    if(violation1 == null)
    violation1 = prev;
    violation2 = root;
    }

    prev = root;
    inorder(root.right);
    }
    public void recoverTree(TreeNode root) {
    inorder(root);

    int temp = violation1.val;

    violation1.val = violation2.val;
    violation2.val = temp;
    }
    }

  • @harshyallewar5876
    @harshyallewar5876 Před 2 lety +1

    Great explain

  • @arsilvyfish11
    @arsilvyfish11 Před 11 měsíci

    Excellent explanation

  • @dhairyashiil
    @dhairyashiil Před 2 lety

    Thank You : )

  • @rounakmukherjee9540
    @rounakmukherjee9540 Před rokem

    We dont need to check the condition if prev!=NULL ;

  • @jaiminsolanki5478
    @jaiminsolanki5478 Před 2 lety

    Understood!

  • @Anonymous-uj3jx
    @Anonymous-uj3jx Před 2 lety

    Understood thanks :)

  • @girikgarg1268
    @girikgarg1268 Před 2 lety

    Is it not possible that there are more than two violations for example three or four violations? Why have we considered that either there will be one violation or two violations?

    • @RaunakKumar-yr3zv
      @RaunakKumar-yr3zv Před 2 lety +10

      Because the question states that only 2 nodes will be swapped

  • @charchitagarwal589
    @charchitagarwal589 Před měsícem

    hey guys'

  • @ashishkumaryadav5252
    @ashishkumaryadav5252 Před rokem +1

    Exceptional.

  • @adarshkumargupta.
    @adarshkumargupta. Před rokem +1

    bhai code bahut tej explain karte ho thoda slow karo yaar

  • @ankurshukla6462
    @ankurshukla6462 Před 2 lety +2

    Why you need to allocate space to prev? I don’t think we need it.

  • @abhiimali
    @abhiimali Před 2 lety

    nice code explanation

  • @gauravshukla5203
    @gauravshukla5203 Před rokem

    If bst is not in correct order you will not get the preorder sorted

  • @UECAshutoshKumar
    @UECAshutoshKumar Před 11 měsíci +1

    Thank you sir

  • @techmoon_
    @techmoon_ Před 2 lety

    Great video

  • @ankitkumarsingh8346
    @ankitkumarsingh8346 Před 2 lety

    striver rescued me here

  • @vibhu613
    @vibhu613 Před 2 lety +1

    Hey interviewer😆😅

  • @dreamyme543
    @dreamyme543 Před rokem

    Understood:)

  • @girikgarg8
    @girikgarg8 Před rokem

    Done!!

  • @user-gq3xu4vj8d
    @user-gq3xu4vj8d Před rokem

    bhaiya you are great

  • @Xp-Sam
    @Xp-Sam Před 2 lety +1

    why are we checking prev != NULL

    • @yashverma2986
      @yashverma2986 Před 2 lety

      tabhi toh compare kr payega bhai swapping ke lie

    • @Xp-Sam
      @Xp-Sam Před 2 lety +2

      Bhai I think prev is never going to be NULL, because at first we are assigning it with INT_MIN and after that it always stores non-null root value.
      Wo condition hata ke dekho code chalega

    • @your_name96
      @your_name96 Před 2 lety

      @@Xp-Sam ha prev ko NULL kar de instead of INT_MIN tabh bhi chalega, my code without middle pointer, easy to optimize if yo examine the conditions in main function:
      class Solution {
      TreeNode *prev;
      TreeNode *first;
      // TreeNode *middle;
      TreeNode *last;
      public:
      void inorder(TreeNode* root){
      if(!root)return;
      inorder(root->left);
      // the node is not the root element
      if(prev != NULL and (root->val < prev->val)){
      // if this is the first element
      if(first == NULL){
      first = prev;
      }
      last = root;
      }
      prev = root;
      inorder(root->right);
      }
      void recoverTree(TreeNode* root) {
      prev = first = middle = last = NULL;
      inorder(root);

      swap(first->val,last->val);

      }
      };

  • @sksp9028
    @sksp9028 Před 11 měsíci

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

  • @amitswami3139
    @amitswami3139 Před 2 lety

    Can I do it using the concept which you are using in the last lecture (largest bst) when the condition get wrong
    largest of left

  • @rks3522
    @rks3522 Před 2 lety

    13:10

  • @audiobooksforyouspark
    @audiobooksforyouspark Před 2 lety

    Wow

  • @jayyy311
    @jayyy311 Před 2 lety

    💚

  • @rohanmadiratta6421
    @rohanmadiratta6421 Před 5 měsíci

    shouldnt first be equal to root..how come first is set equal to prev

  • @harshdasila6680
    @harshdasila6680 Před 11 měsíci

    Goat 🐐

  • @user-up6sl2gq8p
    @user-up6sl2gq8p Před 7 měsíci

    ...............

  • @yatri6329
    @yatri6329 Před rokem

    Baak bakwas krta h Khali kuch sahi se explain nhi krta h

  • @satyamchauhan9775
    @satyamchauhan9775 Před 2 lety

    I have done it in n time and n space using hashmap , and i was thinking my solution is best until i watched this video🥲

  • @kakarotsv50
    @kakarotsv50 Před 9 měsíci

    Awesome explanation

  • @chiragbansod8252
    @chiragbansod8252 Před 4 měsíci

    understood

  • @jagjiwanchimkar8106
    @jagjiwanchimkar8106 Před 2 lety +2

    When this Serie Complete

  • @rishabhgupta9846
    @rishabhgupta9846 Před rokem

    understood