L52. Recover BST | Correct BST with two nodes swapped

  Рет қаралды 137,732

take U forward

take U forward

Күн бұрын

Пікірлер: 131
@takeUforward
@takeUforward 3 жыл бұрын
Please like and share :)
@AdityaSharma-nr7qn
@AdityaSharma-nr7qn 3 жыл бұрын
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 Жыл бұрын
instead of making third variable we can also update the middle variable when there is a 2nd violation
@ujjwalverma5893
@ujjwalverma5893 2 жыл бұрын
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); } }
@PRANAVMAPPOLI
@PRANAVMAPPOLI 2 жыл бұрын
Thought same ✌️💯
@jiteshsingh4899
@jiteshsingh4899 2 жыл бұрын
my mom said "ye ladka kitni mehnat karta h" - what a explanation striver bhaiya
@SatyamKumar-bw4vi
@SatyamKumar-bw4vi 2 жыл бұрын
Hare Krishna..! Got Placed in R & D of a Product Based Company..! Thanks Bhaiya..! I will tag you in Linkedln post in some time
@namratam1522
@namratam1522 Жыл бұрын
You are the best instructor !! Thanks a ton for this content ! You are bringing a revolution striver!
@shinewanna3959
@shinewanna3959 Жыл бұрын
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 Жыл бұрын
In leetcode question the values are in range of [INT_MIN, INT_MAX], so this won't work there.
@stith_pragya
@stith_pragya Жыл бұрын
Thank You So Much for this wonderful video...🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@timjoyalle318
@timjoyalle318 2 жыл бұрын
This dude's neighbors get free lectures. Hope they appreciate it.
@chitranshjain5075
@chitranshjain5075 2 жыл бұрын
Such a brilliant explanation of the problem! Thank you very much fir helping all of us!
@apmotivationakashparmar722
@apmotivationakashparmar722 Ай бұрын
Thank you so much Striver !
@kalpeshmali1476
@kalpeshmali1476 3 жыл бұрын
After watching your tree series i m pretty confident in Binary trees and bst 🔥🔥🔥🔥🔥🔥🔥
@ShilpiKumari-i3s
@ShilpiKumari-i3s 2 жыл бұрын
//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); }
@shashankbajpai5659
@shashankbajpai5659 2 жыл бұрын
add morris traversal and we can do this problem on O(1) space as well.
@SibiRanganathL
@SibiRanganathL Ай бұрын
how
@krishnaradhey2814
@krishnaradhey2814 Жыл бұрын
LeetCode 99 problem Can be done with morris traversal
@dhrutidesai278
@dhrutidesai278 9 ай бұрын
Thankyou sir👍For always helping by your approaches
@aakashgoswami2356
@aakashgoswami2356 2 жыл бұрын
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 2 жыл бұрын
We have to make variable i, a global variable. So, that it can get updated after every recursive call.
@tusharagarwal5306
@tusharagarwal5306 9 ай бұрын
13:55 which online coding judge or editor is that??
@pratikmhatre4815
@pratikmhatre4815 2 жыл бұрын
I always feel motivated by your passion of explaining problems👍
@SharuxD
@SharuxD 2 жыл бұрын
The logic you have given to solve this is brilliant af. GG
@amanbhadani8840
@amanbhadani8840 3 жыл бұрын
Absolutely brilliant explanation as well as mind blowing implementation of code,just loved it bhaiya.
@ZebraZodiac
@ZebraZodiac 7 ай бұрын
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.
@sreekanthyadav5801
@sreekanthyadav5801 6 ай бұрын
For many problems in BST, MORRIS Inorder approach is giving Stack Overflow error (RUN TIME ERROR). Is it same with everybody ?
@stith_pragya
@stith_pragya Жыл бұрын
🚨[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 11 ай бұрын
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
@jerrywong5140
@jerrywong5140 2 жыл бұрын
Very helpful and thorough explanation, love it!
@tempbot7190
@tempbot7190 6 ай бұрын
Much Love from London❤
@Ramu9119
@Ramu9119 11 ай бұрын
excellent explanation striver bhai
@anubhavpabby6856
@anubhavpabby6856 2 жыл бұрын
Thank you striver bhaiya for making such a great series and it's helping me out in placement preparation
@parthsalat
@parthsalat 2 жыл бұрын
You seem to like teddy bears a lot
@Manjot_singh2002
@Manjot_singh2002 3 ай бұрын
15:20 the ans is comming incorrect if we just swap the 49 and 50th line but Y case to un mein se ek hi chlega aggy peeechy sy kya farak pdta hai
@ayushbhargava8400
@ayushbhargava8400 11 ай бұрын
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.
@preetisahani5054
@preetisahani5054 Жыл бұрын
Awesome explanation
@studyafa7159
@studyafa7159 10 ай бұрын
i think there is no need of " prev != null" in line 27
@lavanyaprakashjampana933
@lavanyaprakashjampana933 2 жыл бұрын
we love your content and we love you......🤟🖤
@shagunlamba6481
@shagunlamba6481 3 жыл бұрын
Great explanation , thank you.
@niranjansaha5135
@niranjansaha5135 2 жыл бұрын
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); } }
@prasadm3614
@prasadm3614 Жыл бұрын
Congratulations on 3 Lakh Subscribers
@ishakhutafale1163
@ishakhutafale1163 6 ай бұрын
Watch these videos, and you'll never forget the importance of inorder traversal for BSTs!
@DeadPoolx1712
@DeadPoolx1712 28 күн бұрын
UNDERSTOOD;
@gandhijainamgunvantkumar6783
@gandhijainamgunvantkumar6783 2 жыл бұрын
Thank you so much striver bhaiya for providing such an amazing content :)
@adebisisheriff159
@adebisisheriff159 10 ай бұрын
Thanks Man!!!
@prashantsahu6212
@prashantsahu6212 2 жыл бұрын
Just wow, the intution was awesome.
@Learnprogramming-q7f
@Learnprogramming-q7f 9 ай бұрын
Thank you Bhaiya
@vinaygoswami5374
@vinaygoswami5374 2 жыл бұрын
Quite ambiguous explanation.
@adiin-1940
@adiin-1940 Жыл бұрын
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 Жыл бұрын
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.
@sparshsharma6068
@sparshsharma6068 3 жыл бұрын
Amazing explanation bhaiya!
@16aniketdutta58
@16aniketdutta58 2 жыл бұрын
The middle pointer can be avoided I guess!!!
@placementbaadshah8604
@placementbaadshah8604 2 жыл бұрын
kzbin.info/www/bejne/oWPLkoCqhZyhrNU
@your_name96
@your_name96 2 жыл бұрын
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); } };
@anumoynandy5811
@anumoynandy5811 2 жыл бұрын
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); } };
@philipbrujic4728
@philipbrujic4728 4 ай бұрын
good video
@shantanukumar4081
@shantanukumar4081 2 жыл бұрын
Great Explanation !!!
@DeependraSingh-jh8xf
@DeependraSingh-jh8xf Жыл бұрын
fire hai bhau
@keshavagrawal1027
@keshavagrawal1027 6 ай бұрын
can someone tell me why in the last we do (prev=root ) pls if u know try to give a explanation...🙏
@mohamedosman3120
@mohamedosman3120 4 ай бұрын
Thx
@peddikarthik7832
@peddikarthik7832 Жыл бұрын
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 ?
@jsuryakt
@jsuryakt 3 жыл бұрын
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; } }
@siddhaarthsingh7414
@siddhaarthsingh7414 2 жыл бұрын
Why prev = new Tree(INT_MIN) That is not required !!!! Pls Anyone ???
@arpitjaswal4210
@arpitjaswal4210 2 жыл бұрын
I simply made the prev node NULL and the code still got accepted.
@muditkhanna8164
@muditkhanna8164 Жыл бұрын
but what if there are more than one nodes that are swapped?
@SibiRanganathL
@SibiRanganathL Ай бұрын
Understodd
@chiragbansod8252
@chiragbansod8252 9 ай бұрын
understood
@papayasprout
@papayasprout 2 жыл бұрын
Thanks for the video man.
@spyrowolf2211
@spyrowolf2211 3 жыл бұрын
what drawing software are u using?
@justinmyth4980
@justinmyth4980 3 жыл бұрын
Why you have used middle,we can just update last instead of middle and it works fine??
@placementbaadshah8604
@placementbaadshah8604 2 жыл бұрын
kzbin.info/www/bejne/oWPLkoCqhZyhrNU
@your_name96
@your_name96 2 жыл бұрын
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 2 жыл бұрын
@@your_name96 thanks bro btw which are u a college student?
@mohit9975
@mohit9975 Жыл бұрын
@@justinmyth4980 Islamabad university , lahore
@harshitjaiswal9439
@harshitjaiswal9439 10 ай бұрын
understood.
@JujareVinayak
@JujareVinayak 2 жыл бұрын
Which device is used in videos?? I need one to practice.
@BhuwanSaretia
@BhuwanSaretia 2 ай бұрын
Instead of using the middle pointer, we can solve this using only two pointers. Here is the detailed solution class Solution { public: TreeNode* prev = NULL; TreeNode* first = NULL; TreeNode* second = NULL; void inOrder(TreeNode*& root) { if (root == NULL) return; inOrder(root->left); if (prev == NULL) prev = root; else { if (prev->val > root->val) { if (first == NULL) { first = prev; second = root; } else { second = root; } } } prev = root; inOrder(root->right); } void recoverTree(TreeNode* root) { inOrder(root); if (first == NULL) return; swap(first->val, second->val); return; } };
@ankurshukla6462
@ankurshukla6462 3 жыл бұрын
Why you need to allocate space to prev? I don’t think we need it.
@placementbaadshah8604
@placementbaadshah8604 2 жыл бұрын
kzbin.info/www/bejne/oWPLkoCqhZyhrNU
@silicon9794
@silicon9794 2 жыл бұрын
Perfectly explained....
@fazilshafi8083
@fazilshafi8083 4 ай бұрын
Java Solution 👇 class Solution { private TreeNode firstViolation = null; private TreeNode adjacentToViolation = null; private TreeNode secondViolation = null; private TreeNode prev = null; private void swap(TreeNode a, TreeNode b) { int temp = a.val; a.val = b.val; b.val = temp; } private void helper(TreeNode root) { if (root == null) { return; } // Traverse the left subtree helper(root.left); // Check for violations if (prev != null && root.val < prev.val) { if (firstViolation == null) { firstViolation = prev; adjacentToViolation = root; } else { secondViolation = root; } } // Update prev to current node prev = root; // Traverse the right subtree helper(root.right); } public void recoverTree(TreeNode root) { helper(root); if (secondViolation == null) { swap(firstViolation, adjacentToViolation); } else { swap(firstViolation, secondViolation); } } }
@arsilvyfish11
@arsilvyfish11 Жыл бұрын
Excellent explanation
@ErfanHossainShoaib
@ErfanHossainShoaib 2 жыл бұрын
If the inorder sequence is 3 25 7 8 10 15 20 12. Then...
@jagjiwanchimkar8106
@jagjiwanchimkar8106 3 жыл бұрын
When this Series Complete
@harshyallewar5876
@harshyallewar5876 2 жыл бұрын
Great explain
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir
@jagjiwanchimkar8106
@jagjiwanchimkar8106 3 жыл бұрын
When this Serie Complete
@takeUforward
@takeUforward 3 жыл бұрын
Tomorrow..
@jagjiwanchimkar8106
@jagjiwanchimkar8106 3 жыл бұрын
@@takeUforward cool
@ashishkumaryadav5252
@ashishkumaryadav5252 Жыл бұрын
Exceptional.
@shivambajpeyi9008
@shivambajpeyi9008 3 жыл бұрын
this was smooth!
@sksp9028
@sksp9028 Жыл бұрын
``` 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); } }; ```
@dhairyashiil
@dhairyashiil 2 жыл бұрын
Thank You : )
@abhaykumarsingh3884
@abhaykumarsingh3884 3 ай бұрын
Don't use middle pointer just 2nd one if found /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { TreeNode ptr1=null; TreeNode ptr2=null; TreeNode prev=null; public void getAns(TreeNode root){ if(root==null){ return; } getAns(root.left); if(prev != null && root.val< prev.val){ if(ptr1==null){ ptr1 =prev; ptr2=root; } else{ ptr2=root; } } prev=root; getAns(root.right); } public void recoverTree(TreeNode root) { getAns(root); int temp=ptr1.val; ptr1.val=ptr2.val; ptr2.val=temp; } }
@adarshkumargupta.
@adarshkumargupta. 2 жыл бұрын
bhai code bahut tej explain karte ho thoda slow karo yaar
@vibhu613
@vibhu613 2 жыл бұрын
Hey interviewer😆😅
@Xp-Sam
@Xp-Sam 2 жыл бұрын
why are we checking prev != NULL
@yashverma2986
@yashverma2986 2 жыл бұрын
tabhi toh compare kr payega bhai swapping ke lie
@Xp-Sam
@Xp-Sam 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 2 жыл бұрын
@@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); } };
@rounakmukherjee9540
@rounakmukherjee9540 Жыл бұрын
We dont need to check the condition if prev!=NULL ;
@Anonymous-uj3jx
@Anonymous-uj3jx 2 жыл бұрын
Understood thanks :)
@gauravshukla5203
@gauravshukla5203 Жыл бұрын
If bst is not in correct order you will not get the preorder sorted
@charchitagarwal589
@charchitagarwal589 6 ай бұрын
hey guys'
@abhiimali
@abhiimali 2 жыл бұрын
nice code explanation
@AnkitPandey-s9h
@AnkitPandey-s9h Жыл бұрын
bhaiya you are great
@rks3522
@rks3522 2 жыл бұрын
13:10
@jaiminsolanki5478
@jaiminsolanki5478 3 жыл бұрын
Understood!
@ankitkumarsingh8346
@ankitkumarsingh8346 3 жыл бұрын
striver rescued me here
@girikgarg1268
@girikgarg1268 3 жыл бұрын
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 3 жыл бұрын
Because the question states that only 2 nodes will be swapped
@techmoon_
@techmoon_ 2 жыл бұрын
Great video
@rishabhgupta9846
@rishabhgupta9846 Жыл бұрын
understood
@harshdasila6680
@harshdasila6680 Жыл бұрын
Goat 🐐
@dreamyme543
@dreamyme543 2 жыл бұрын
Understood:)
@rohanmadiratta6421
@rohanmadiratta6421 10 ай бұрын
shouldnt first be equal to root..how come first is set equal to prev
@ajayypalsingh
@ajayypalsingh 2 жыл бұрын
💚
@girikgarg8
@girikgarg8 Жыл бұрын
Done!!
@amitswami3139
@amitswami3139 2 жыл бұрын
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
@placementbaadshah8604
@placementbaadshah8604 2 жыл бұрын
kzbin.info/www/bejne/oWPLkoCqhZyhrNU
L53. Largest BST in Binary Tree
17:27
take U forward
Рет қаралды 170 М.
L38. Flatten a Binary Tree to Linked List | 3 Approaches | C++ | Java
21:51
Who is More Stupid? #tiktok #sigmagirl #funny
0:27
CRAZY GREAPA
Рет қаралды 10 МЛН
I'VE MADE A CUTE FLYING LOLLIPOP FOR MY KID #SHORTS
0:48
A Plus School
Рет қаралды 20 МЛН
G-46. Disjoint Set | Union by Rank | Union by Size | Path Compression
42:15
Joobi SB - Mastering Concurrency in Go: From Patterns to Production
24:12
Emerging Technology Trust
Рет қаралды 272
G-14. Surrounded Regions | Replace O's with X's | C++ | Java
23:17
take U forward
Рет қаралды 199 М.
The Dome Paradox: A Loophole in Newton's Laws
22:59
Up and Atom
Рет қаралды 272 М.
Pointers in C / C++ [Full Course]
3:47:23
freeCodeCamp.org
Рет қаралды 4,8 МЛН
L4. Implement Min Stack | Stack and Queue Playlist
20:55
take U forward
Рет қаралды 53 М.
2.6.3 Heap - Heap Sort - Heapify - Priority Queues
51:08
Abdul Bari
Рет қаралды 2,2 МЛН
L28. Maximum Width of Binary Tree | C++ | Java
22:41
take U forward
Рет қаралды 281 М.
Who is More Stupid? #tiktok #sigmagirl #funny
0:27
CRAZY GREAPA
Рет қаралды 10 МЛН