L47. LCA in Binary Search Tree

  Рет қаралды 133,239

take U forward

take U forward

Күн бұрын

Entire DSA Course: takeuforward.o...
Check our Website:
Linkedin/Instagram/Telegram: linktr.ee/take...
#treeSeries #striver #placements

Пікірлер: 126
@takeUforward
@takeUforward 3 жыл бұрын
Please do like and share among your friends!! ^ _ ^
@danceofficial3912
@danceofficial3912 3 жыл бұрын
Kehne ki baat hai yeh bhii
@divyansh2212
@divyansh2212 2 жыл бұрын
Iterative Code: TreeNode *LCAinaBST(TreeNode *root, TreeNode *p, TreeNode *q) { while (root) { if (root->data > p->data && root->data > q->data) root = root->left; else if (root->data < q->data && root->data < p->data) root = root->right; else return root; } return NULL; }
@SriHarshaChilakapati
@SriHarshaChilakapati 3 жыл бұрын
This solution is optimal and works only when the constraint that both the nodes are actually in the tree. While not a better approach than the one shown in this video, I went with implementing a visitor pattern to cover the case where any node is not in the tree. This brings the TC to O(H) and SC to O(H) as well. The idea is to keep an expanding array. During the visit to search first item, we add the value to the array at the end. If not found, return null then and there. Now, initialize a variable idx to -1. Then search for second item, and while visiting each node, check if the array[idx + 1] element is the same as the current node. If yes, increment idx. Finally if the node is not found, or if idx stays at -1, return null. Else you can return array[idx] which is the LCA.
@crazycr7331
@crazycr7331 2 жыл бұрын
He had cover this edge test case on Previous LCA video
@galleryofjatin19
@galleryofjatin19 2 жыл бұрын
i have been watching this playlist from last 2 week and practicing problems, but now when you tell the split approach i was just stunned and rn im at @5:12 , I paused the video and writing this comment ! Seriously India need more brilliant mentors and teachers like you!
@kushalroy9747
@kushalroy9747 Жыл бұрын
Man u are right. I was stunned for a sec!!
@VikasGupta-ok9lh
@VikasGupta-ok9lh Жыл бұрын
Same man
@nikhilmadaan29
@nikhilmadaan29 6 ай бұрын
exactly same experience
@shubhamkumarsingh8818
@shubhamkumarsingh8818 5 ай бұрын
man, u r genius. what a brilliant way of teaching.
@karthik-varma-1579
@karthik-varma-1579 Ай бұрын
Thanks Stirver for Tree ka playlist i was able to solve this problem by myself. Thanks a lot.
@prajapati-suraj
@prajapati-suraj 3 ай бұрын
I struggled for 2 hours because I was considering bst as bt.... thank you so much for this...
@aaluSandwich
@aaluSandwich 3 жыл бұрын
Hope the haters watch the video once instead of just barging and disliking. Thank you so much bhaiya for such amazing content.
@VinayKumar-ze2ww
@VinayKumar-ze2ww 2 жыл бұрын
This guy has haters? He is an inspiration bro🙂
@SibiRanganathL
@SibiRanganathL 22 күн бұрын
Great approach
@priyankasetiya1358
@priyankasetiya1358 5 ай бұрын
·class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root==null){ return null; } int current = root.val; if(currentq.val){ return lowestCommonAncestor(root.left,p,q); } else{ return root; } } }
@culeforever5408
@culeforever5408 9 ай бұрын
Great Series 😀
@diegolikescode
@diegolikescode 9 ай бұрын
Man, really good stuff!! Thank you for this!
@amanjotsingh5876
@amanjotsingh5876 2 жыл бұрын
Good explanation .... just one thing bro control your hands movement 😂😂 ... jokes apart..... keep up the good work
@vivekjaiswar6825
@vivekjaiswar6825 3 жыл бұрын
Hey striver i followed your entire tree series but still i can't remember some of the concepts in previous videos. What should i do?
@takeUforward
@takeUforward 3 жыл бұрын
Notes..
@real-investment-banker
@real-investment-banker 2 жыл бұрын
And Revision...
@codding32world50
@codding32world50 2 жыл бұрын
Same here buddy no one can except if you are prodigy... SO REVISION IS THE KEY
@avanishmaurya2034
@avanishmaurya2034 10 ай бұрын
Nice
@subirkumar6786
@subirkumar6786 Жыл бұрын
What if node p is present and node q is not present in the BST
@GauravGangwar-r2v
@GauravGangwar-r2v 5 ай бұрын
bro is genius .
@priyankaranawat8373
@priyankaranawat8373 3 ай бұрын
Thank you sooooo much
@ishwaripednekar5164
@ishwaripednekar5164 2 жыл бұрын
Keep it up, we need teachers like you!!
@aaranyaksantra9933
@aaranyaksantra9933 4 ай бұрын
nice solution
@himanshidafouty347
@himanshidafouty347 4 ай бұрын
Understood
@Preethamdivakar
@Preethamdivakar 4 ай бұрын
super explaination bro🙏
@shwetanksingh5208
@shwetanksingh5208 2 жыл бұрын
//Iterative code with less number of comparisons and no stack space class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { int minVal = min(p->val,q->val),maxVal = max(p->val,q->val); while(root) { if(root->valright;//both values are on right of current node else if(root->val>maxVal) root = root->left;//both values are on left of current node else break;//this node is LCA of p and q } return root; } };
@nishant1720
@nishant1720 Жыл бұрын
what in the case of skewed tree like 1->right = 2, 2->right = 3;
@apmotivationakashparmar722
@apmotivationakashparmar722 Ай бұрын
Thank you So much !
@zeyadalbadawy2245
@zeyadalbadawy2245 Жыл бұрын
Amazing sir
@arpanseal5722
@arpanseal5722 Жыл бұрын
Hello sir, thanks for providing such amazing video tutorials. I can't understand why are you writing the base case here? Is there any need to do that?
@takeUforward
@takeUforward Жыл бұрын
You can ignore if it works without them, I usually write it for cleaner code
@arpanseal5722
@arpanseal5722 Жыл бұрын
@@takeUforward Thank you sir. Got it. ❤️
@GhostVaibhav
@GhostVaibhav 9 ай бұрын
Understood🔥
@Shubham-yc6nz
@Shubham-yc6nz 3 ай бұрын
Thanks
@babai2196
@babai2196 2 жыл бұрын
can this approach be applied to lca of binary tree
@khitijkarmakar
@khitijkarmakar Жыл бұрын
nope
@iamnottech8918
@iamnottech8918 4 ай бұрын
Wow!
@Learnprogramming-q7f
@Learnprogramming-q7f 8 ай бұрын
thank you Bhaiya
@hakunamatata-nl4js
@hakunamatata-nl4js 5 ай бұрын
thank you
@ishangujarathi10
@ishangujarathi10 Жыл бұрын
loved the intuition, amazing explanation as alwaysss!!!! tysm!!!
@arpanbanejee5143
@arpanbanejee5143 3 жыл бұрын
Thanks for this awesome series! you are the best!
@harshitjaiswal9439
@harshitjaiswal9439 9 ай бұрын
understood
@ashishchandra4078
@ashishchandra4078 2 жыл бұрын
crystal clear explanation. Thank you Striver.
@swayam50
@swayam50 3 жыл бұрын
Amazing video as always, you're tree series is helping a lot 🙂🙂
@shikharai-tl4vb
@shikharai-tl4vb 5 ай бұрын
good job :)
@saranguru6100
@saranguru6100 3 жыл бұрын
Hi Striver, if the same question is extended and if they given an array of nodes and if asked to find lca? How to do?
@ashpreetsidana6674
@ashpreetsidana6674 2 жыл бұрын
build the BST from array(you need to sort an array) and then perform LCA
@saranguru6100
@saranguru6100 2 жыл бұрын
​@@ashpreetsidana6674 This consume too much time I guess!! Any efficeient way ?
@editorera239
@editorera239 3 жыл бұрын
bhai kaafi pro level intuition h Thanks!
@ashuraj1981
@ashuraj1981 2 жыл бұрын
Do u read every comments striver, just asking.By the way thanks a lot for #FreekaTreeSeries❤
@akashnandi1267
@akashnandi1267 Жыл бұрын
1 is missing bro pls correct it
@RAJKUMAR-q4c2x
@RAJKUMAR-q4c2x 10 ай бұрын
what if p and q are not present in BST ??
@codebits2120
@codebits2120 2 жыл бұрын
Very clear explanation
@rishabhprasad8333
@rishabhprasad8333 3 жыл бұрын
In the code, if we do not write 'return' before recursive calling the lowestCommonAncestor function, then also it is giving correct output. Then what's the purpose of writing it?
@MeenakshiSharma-bd3bu
@MeenakshiSharma-bd3bu 2 жыл бұрын
No it's not working if you do not write return before recursive call bcz if you will not write return than it will return actual root of bst at the end so its mandatory to write return before recursion as than it will return the root of LCA
@lakshayrastogi2347
@lakshayrastogi2347 2 жыл бұрын
phele se sb krke baitha h bhai? : (
@chirlasowmyareddy
@chirlasowmyareddy Жыл бұрын
geeks for geeks accepted solution using while loop ...hope this helps... Node* LCA(Node *root, int n1, int n2) { //Your code here while(root){ if(root->data==n1 || root->data==n2) { return root; } else if(root->data>n1 && root->datadatadata>n2){ return root; } else if(root->data>n1){ root=root->left; } else{ root=root->right; } } }
@thebibeksaha
@thebibeksaha 2 жыл бұрын
It's my solution but it takes O(2h) extra space and O(n) time class Solution { private void fillSet(TreeNode root, TreeNode targetNode, Set set) { TreeNode curr = root; while (curr != targetNode) { set.add(curr); if (targetNode.val < curr.val) curr = curr.left; else curr = curr.right; } set.add(curr); } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) return null; Set setOne = new LinkedHashSet(); Set setTwo = new LinkedHashSet(); fillSet(root, p, setOne); fillSet(root, q, setTwo); setOne.retainAll(setTwo); TreeNode lca = null; for (TreeNode node : setOne) lca = node; return lca; } }
@parthsalat
@parthsalat 2 жыл бұрын
Here are my detailed notes on this question: garmadon.notion.site/Lowest-Common-Ancestor-of-a-Binary-Search-Tree-f568d9e1505f4234bdbd045516e0d4e5
@tech_wizard9315
@tech_wizard9315 3 жыл бұрын
I am a DSA beginner,is your trees series enough to crack tech giant's like Microsoft linkedin level companies?
@Kpriyasing
@Kpriyasing 3 жыл бұрын
Thanks for such a nice explanation!
@krishnarajs929
@krishnarajs929 2 жыл бұрын
if the given p and q nodes is not there .what we need to do?
@optimus_prime01
@optimus_prime01 Жыл бұрын
return -1
@kwakubiney5175
@kwakubiney5175 Жыл бұрын
Why does it work without the base case check? It works well without `if root == null{return root;}`
@priyanshshah6126
@priyanshshah6126 Жыл бұрын
because both the nodes exists in the tree is the criteria in leetcode
@prachigupta2430
@prachigupta2430 Жыл бұрын
Thanks for this much amazing content and explanation. Again very grateful 😊
@ishaanchandak1258
@ishaanchandak1258 Жыл бұрын
link of the question ?
@deepakojha3216
@deepakojha3216 3 жыл бұрын
bhaiya Dp kab se ayegi .... tree is about to finish i think ...!! few videos left ......Loved your tree series eagerly waiting for the DP series..... please upload it soon...!! you promised us to upload DP on DIWALI...!!
@takeUforward
@takeUforward 3 жыл бұрын
I promised if you give me 10k likes, you did not 🥲 Anyways will be up from Dec 1
@PrinceKumar-el7ob
@PrinceKumar-el7ob 3 жыл бұрын
@@takeUforward bhaiya thodi jldi november m hi upload krdo placement season hai december m 😿. like to bhaiya aa jayenge content hi aise hai 💓.
@dipeshsaili4468
@dipeshsaili4468 2 жыл бұрын
@@takeUforward apne mera resume roast kardia pr purra nhi dekha :c
@_PB03
@_PB03 2 жыл бұрын
//clean iterative code class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { while(root){ if(root->val > p->val && root->val > q->val) root = root->left; else if(root->val < p->val && root->val < q->val) root = root->right; else break; } return root ; } };
@himanshuranjan8657
@himanshuranjan8657 2 жыл бұрын
Line 13 should be : if(root == NULL) return root ;
@igaming_
@igaming_ 2 жыл бұрын
U can write return null or return root (both are correct)
@prafuljohn15
@prafuljohn15 2 жыл бұрын
Striver bhai c++ pr chal nahi raha hai aapka code
@iamnoob7593
@iamnoob7593 9 ай бұрын
US
@ishwaripednekar5164
@ishwaripednekar5164 2 жыл бұрын
This is just outstanding
@shivalikagupta3433
@shivalikagupta3433 2 жыл бұрын
Thank you so mcuh for all your hard work !!!
@DevanshuAugusty
@DevanshuAugusty Жыл бұрын
tc = logn right?
@only_for_fun1234r
@only_for_fun1234r Жыл бұрын
No, think of shew bst it will be o(n)
@DevanshuAugusty
@DevanshuAugusty Жыл бұрын
@@only_for_fun1234r yes you are right . thanx
@sammedpatil3907
@sammedpatil3907 2 жыл бұрын
nice explanation....
@SiddheshKukade
@SiddheshKukade Жыл бұрын
thanks
@player-te8tf
@player-te8tf 2 жыл бұрын
striver runs java code in c++ mode (7:52) on leetcode, halke me mt lena god hai bro apna
@deeyasings
@deeyasings 2 жыл бұрын
understood
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir
@anonymous090
@anonymous090 Жыл бұрын
Thank you Bhaiya
@sayakbasak587
@sayakbasak587 Жыл бұрын
thanks bhaiya
@debugagrawal
@debugagrawal 2 жыл бұрын
DSA God 😍🙌🚩🚀
@alesblaze4745
@alesblaze4745 2 жыл бұрын
thanks mate!
@venutalla5932
@venutalla5932 Жыл бұрын
Tq sir
@roopeshn3301
@roopeshn3301 2 жыл бұрын
Understood
@atifali3485
@atifali3485 5 күн бұрын
Is this correct? TC-> O(H) SC-> O(1) // Iterative soltion class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while(true){ if(root==null) return null; if((root.val>p.val && root.val p.val && root.val>p.val) root=root.left; else root=root.right; } } }
@bhaveshrathod9898
@bhaveshrathod9898 2 жыл бұрын
Thanks for the video:)
@abhishek__anand__
@abhishek__anand__ Жыл бұрын
Super
@ajayypalsingh
@ajayypalsingh 2 жыл бұрын
💚
@BharatVaad
@BharatVaad 2 жыл бұрын
great
@rishabhgupta9846
@rishabhgupta9846 Жыл бұрын
able to solve by myself
@NikhilGupta-zo5jh
@NikhilGupta-zo5jh 2 жыл бұрын
UnderStood
@piyushacharya7696
@piyushacharya7696 2 жыл бұрын
// Iterative Approach JAVA: Beats 100%🔥 package DataSructures.BST; public class LCAInBST { // time complexity: O(height) -> not recommended to use the BT way of solving, since it gives tc of O(n) public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode lca = findNode(root, p, q); return lca; } private TreeNode findNode(TreeNode root, TreeNode p, TreeNode q) { if (root == null) return null; while (root != null) { // this ensures that we reach the lca. Using the property of BST if (root.val >= Math.min(p.val, q.val) && root.val = Math.max(p.val, q.val)) { root = root.left; } else { root = root.right; } } return root; } }
@tejalsaraswat
@tejalsaraswat Жыл бұрын
u r the besttt
@aditya14-02
@aditya14-02 3 жыл бұрын
Awesome code,video keep it uo
@605_samikrdas4
@605_samikrdas4 Жыл бұрын
soooo goood trulyyy
@suvanshmahajan5902
@suvanshmahajan5902 2 жыл бұрын
"us"
@dreamyme543
@dreamyme543 2 жыл бұрын
Understood:)
@theonlyisteve7261
@theonlyisteve7261 2 жыл бұрын
shit got real, nice1
@ashutoshtripathi8257
@ashutoshtripathi8257 3 жыл бұрын
🔥🔥❤️
@hitheshpk6030
@hitheshpk6030 3 ай бұрын
Understood
@abhinanda7049
@abhinanda7049 6 ай бұрын
understood
@tech_wizard9315
@tech_wizard9315 3 жыл бұрын
I am a DSA beginner,is your trees series enough to crack tech giant's like Microsoft linkedin level companies?
@deepakojha3216
@deepakojha3216 3 жыл бұрын
hell,yes...!!
@tanishkumar6682
@tanishkumar6682 Жыл бұрын
understood
@tanmayjain5576
@tanmayjain5576 Жыл бұрын
Understood
@adityapandey23
@adityapandey23 2 ай бұрын
Understood
@Shivi32590
@Shivi32590 3 ай бұрын
understood
L48. Construct a BST from a preorder traversal | 3 Methods
16:32
take U forward
Рет қаралды 175 М.
L27. Lowest Common Ancestor in Binary Tree | LCA | C++ | Java
14:09
take U forward
Рет қаралды 328 М.
ТВОИ РОДИТЕЛИ И ЧЕЛОВЕК ПАУК 😂#shorts
00:59
BATEK_OFFICIAL
Рет қаралды 7 МЛН
How Much Tape To Stop A Lamborghini?
00:15
MrBeast
Рет қаралды 248 МЛН
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 445 М.
Lowest Common Ancestor of a binary tree | Leetcode #236
17:29
2 Years of C++ Programming
8:20
Zyger
Рет қаралды 5 М.
Inorder Successor in a binary search tree
17:58
mycodeschool
Рет қаралды 362 М.
L52. Recover BST | Correct BST with two nodes swapped
15:56
take U forward
Рет қаралды 134 М.
500 Days REMAIN in HARDCORE Minecraft...
1:04:52
SB737
Рет қаралды 145 М.
L51. Two Sum In BST | Check if there exists a pair with Sum K
15:06
take U forward
Рет қаралды 153 М.
Fastest way to learn Data Structures and Algorithms
8:42
Sahil & Sarra
Рет қаралды 262 М.