Тёмный

L27. Lowest Common Ancestor in Binary Tree | LCA | C++ | Java 

take U forward
Подписаться 595 тыс.
Просмотров 262 тыс.
50% 1

Entire DSA Course: takeuforward.org/strivers-a2z...
Check our Website:
Linkedin/Instagram/Telegram: linktr.ee/takeUforward
#treeSeries #striver #placements

Опубликовано:

 

28 авг 2021

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 282   
@takeUforward
@takeUforward 2 года назад
Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79
@rahulsrivastava1040
@rahulsrivastava1040 2 года назад
Understooooooooooooooood :) and done everything thank u so much striver :)
@dipeshsaili4468
@dipeshsaili4468 2 года назад
Do TreeNode* left and right take space? I mean definitely there's pointer to heap/ dynamically
@gshreyaa
@gshreyaa 2 года назад
Will this approach work if numbers are not present in the tree?
@vivekparashar...8716
@vivekparashar...8716 2 года назад
done bro
@ToonTorque
@ToonTorque Год назад
Can you please help me out on this as this question is asked in my interview @takeUforward AMY AND SCHOOL Problem Statement Wizard-Land can be represented as infinite line with coordinates ….., -3, -2, -1, 0, 1, 2, 3 … and so on. Amy teaches in a school with N batches of students. Ai denotes the number of students in the ith batch. Amy has to choose one coordinate as school and one coordinate for each batch of students as their hostel. Students of same batch lives in one hostel. All the N+1, coordinates chosen by her must be distinct. Each morning students walks from their hostel to the school. If the student’s hostel is at coordinate XH and school is at coordinate XS, then he travels | XS - XH | units of distance. She wants to assign these N+1, coordinates such that total distance travelled by each student to reach the school in morning is minimized. Find the minimum total distance. You are given T independent test cases. Constraints 1
@sleepypanda7172
@sleepypanda7172 2 года назад
Every other RU-vidr just speaks the code out, it's only you who focus on explaining the question by manually drawing and dry running it. That's the identity of a real hero. Thanks a lot.
@vishalgowrav
@vishalgowrav Год назад
Understood!! PS:- You will be given a two nodes and you need to return LCA of those two nodes. Solution approach:- Use DFS traversal(Recursive DFS) first go to left and then go to right. 0) If the root node is only one the node which you are looking for then return root 1) If both left and right returns null then returns null 2) If left returns a node and right returns null then return left and vice versa (Return something which gives u node) 3) If both returns you the nodes then u have found the answer so return root Code:- class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root==null || root==p || root==q){ return root; } TreeNode left=lowestCommonAncestor(root.left,p,q); TreeNode right=lowestCommonAncestor(root.right,p,q); if(left==null){ return right; } else if(right==null){ return left; } else{ return root; } } }
@human75788
@human75788 2 года назад
I watched about 4 minutes of your video and coded it myself.. Your explanation is just heaven .
@als_venky7057
@als_venky7057 Год назад
but the real part starts after 4minutes😂
@nishankjain88
@nishankjain88 Год назад
@@als_venky7057 😂😂
@rohanverma3111
@rohanverma3111 Год назад
@@als_venky7057 xD 😂😂😂😂
@only_for_fun1234r
@only_for_fun1234r Год назад
@@als_venky7057 😅😅
@SlapB0X
@SlapB0X 9 месяцев назад
that approach should not be done.. watch the latter half for the optimal approach
@vinaygupta2369
@vinaygupta2369 Год назад
Striver bhai rocked.. buddy you are helping thousands of folks like me preparing for DSA interview. :)
@_who__knows__16
@_who__knows__16 2 года назад
Thanks a lot for contributing to the community. Nicely understood!!!
@knowthrvdo
@knowthrvdo 26 дней назад
i am solving question by myself without watching lec bcoz of youre awosome lectures thank you keep it up!!
@kartiksaini5619
@kartiksaini5619 2 года назад
The best explantion 🔥🔥🔥🏅 really loved it🔥🔥I must say this is your best video
@surajpalsau870
@surajpalsau870 Год назад
Best solution, After 5 minutes of understanding, I got that why we don't need to go forward after getting anyone of the descendants. hats off🤠
@dikshasoni52a98
@dikshasoni52a98 Месяц назад
Can u tell why we don't have to go further ... I didn't get it ........ What if 7 is on left or right of 4 ......
@devvikramsingh7785
@devvikramsingh7785 Месяц назад
@@dikshasoni52a98 Because If 7 is on left of 4 then 4 will be LCA .So no need to go down as we will either get NULL or p or q or some common node (root) nothing else
@ayush52905
@ayush52905 2 года назад
hey @take U forward, i dont usualy comment here but its really motivating to see you hustle so much. We get to learn a lot from your personality.
@HoneyComb1711
@HoneyComb1711 21 день назад
Thank you very much! Striver is the best channel! I refer only to striver videos!
@ishangujarathi10
@ishangujarathi10 Год назад
the optimized approach was awesome, loves the intuition !!! easyily understood
@mukitmahmudul2616
@mukitmahmudul2616 2 месяца назад
Your explanations are truly remarkable and have greatly helped me in understanding complex concepts more clearly. Your dedication to simplifying intricate topics and your engaging teaching style make learning DSA both enjoyable and enlightening. Take love sir.
@harishsn4866
@harishsn4866 2 года назад
Simple and lucid explanation. Thanks, bro.
@349_rahulbhattacharya6
@349_rahulbhattacharya6 2 года назад
best explanation till date!!Vey very very easily understood as a noob coder.Thanks a lot!!
@charlesbabbage6786
@charlesbabbage6786 2 месяца назад
Beautifully explained!!
@giridharjadala2182
@giridharjadala2182 2 года назад
In the third case, i guess lca(2,6) would be 1 because the proper ancestor of n is any node y such that node y is an ancestor of node n and y is not the same node as n.
@echocoding4550
@echocoding4550 8 месяцев назад
u work is really helping us to understand this type of concept. So thank u !!
@rushidesai2836
@rushidesai2836 6 дней назад
Classic binary tree question! Thanks Striver.
@ManojKumar-jb4sc
@ManojKumar-jb4sc 2 года назад
Nicely explained and easily underatood
@thegreekgoat98
@thegreekgoat98 2 года назад
Such a cool teaching... and an awesome logic.
@manasdeora4601
@manasdeora4601 2 года назад
Amazing man.. the last line was what i was not able to understand, i.e. if both are not null,then return root. Thankyou bro.
@jinhuang7258
@jinhuang7258 8 месяцев назад
You are so good. Thank you!
@imranimmu4714
@imranimmu4714 10 месяцев назад
I could never think, of such a great Idea. I approached this probelm in different way. We can level order traverse each node to find the nodes parent and the level they are in. so, for the given 2 nodes, the node which is higher level can be taken up to the level of node in lower level. After this, in each iteration of leel decrement, keep check if we found a mtach between those 2 node. if yes, return the answer, other wise, keep decrementing level, by moving to the parent node.
@RahulPatel-hr4qe
@RahulPatel-hr4qe 2 дня назад
what is thought was of do two dfs for each node notice the path of each and then run a check on the path of the string
@stith_pragya
@stith_pragya 6 месяцев назад
Thank You So Much for this wonderful video........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@roshnisingh7364
@roshnisingh7364 4 месяца назад
very well explained !! Thanks
@neelpatel122
@neelpatel122 2 года назад
Explanation is flawless. keep it up.
@amanpahari690
@amanpahari690 Месяц назад
thanks bro, your dry run was great,, was struggling to visualize recurssion
@rishabhgupta9846
@rishabhgupta9846 Год назад
Understood,able to solve by brute force and with optimized approach after getting a hint.Thank you striver
@cinime
@cinime Год назад
Understood! Super amazing explanation as always, thank you very much!!
@nelsonoboo5423
@nelsonoboo5423 Год назад
I never comment on vedio, but this was extremely sweet to go uncommented. I love how you articulate every step, you are a saviour brother
@nikhilnagrale
@nikhilnagrale 2 года назад
// Code For Naive Solution class Solution { bool getPath(TreeNode* root, TreeNode* x, vector &path) { if (root == NULL) return false; path.push_back(root); if(root == x) return true; if (getPath(root->left, x, path) || getPath(root->right, x, path)) return true; path.pop_back(); return false; } vector getPathtoNode(TreeNode* A, TreeNode* B) { vector path; if (A == NULL) return path; getPath(A, B, path); return path; } TreeNode* findLastCommon(vector a,vector b){ TreeNode *lastCommon=NULL; for(int i=0;i
@parul8334
@parul8334 Год назад
Love This solution
@rushyya
@rushyya 9 месяцев назад
UNDERSTOOD! THANK YOU🙌
@yashgarg8921
@yashgarg8921 7 месяцев назад
beautiful explanation my man.
@Mayanksingh-qp6dy
@Mayanksingh-qp6dy 2 года назад
I've watched this video 5 times to understand the concept 😅. Just want to thank u bhaiya for such an fabulous explanation and amazing content.
@surendradas8174
@surendradas8174 2 года назад
Wow I was able to write the code myself just after explanation.
@devanshubilthare5277
@devanshubilthare5277 2 года назад
Great Explanation, loving the series so far
@soumalyadhar.28
@soumalyadhar.28 2 года назад
too smooth too good...amazing explanation...thank you STRIVER
@jajateenandineesahoo259
@jajateenandineesahoo259 2 года назад
Never thought that the solution for this question will be so simple and easy to understand.
@170_akashgupta_cse2
@170_akashgupta_cse2 Год назад
Bhai ismei simple kya tha 😢
@shivaliraghav8524
@shivaliraghav8524 2 года назад
very easy to follow explanation!
@OIAOa
@OIAOa 4 месяца назад
crystal clear sir
@pragyapal4258
@pragyapal4258 2 года назад
superb explanation!!! it made trees very easy for me. Thank you so much.
@uRamPlus
@uRamPlus 2 года назад
your on a different level !!! thank you 💎
@shivangisrivastava1158
@shivangisrivastava1158 2 года назад
Totally clear, loving this series. Thanks a ton for making this.❤️
@tanyagupta4247
@tanyagupta4247 2 года назад
I tried to understand the logic by myself for 2 times and then coded it without seeing anyone's code. Feeling so good💗
@electronx5594
@electronx5594 2 года назад
heyy same, but why are you here then🤔
@parthsalat
@parthsalat Год назад
@@electronx5594 Just to comment this. 😄
@prachimatta
@prachimatta 2 месяца назад
Excellent
@nilanjanmajumder8508
@nilanjanmajumder8508 2 года назад
great video .... very nicely explained ...... just loved it ❤
@ayushpatel2171
@ayushpatel2171 2 года назад
The solution was great but I think it wont give right answer if the other node is not in the tree. In that case we have to do brute force only I think. Edit: I just saw the leetcode question of this video and it was mentioned that it is guaranteed that p and q will be present in the tree.
@BTECSPRAKASHSINGH
@BTECSPRAKASHSINGH 2 года назад
Striver ,your videos are perfect.
@fazilshafi8083
@fazilshafi8083 3 месяца назад
Thank you! 😇
@sonukumarpandit9731
@sonukumarpandit9731 Год назад
Hey striver, Space Complexity of first approach should O(H) for each call because at maximum we can have nodes equal to the height of the tree. Thanks for the lecture.
@vivekveman4961
@vivekveman4961 2 года назад
Best ever solution for this problem!
@mohit7717
@mohit7717 9 дней назад
Thansk a lot for both approaches.............Most of us think that ....what if p and q both on the same path then ?... Like if p and q on the same path then, first whether p or q meet on that path and return that and no need to go further onthat path and all other root will then return null ...SO as Striver said, if either of null then we return value part.. so we got answer in this case too. Can there will be a duplicate node too @striver?
@vishalpatil3995
@vishalpatil3995 3 месяца назад
Nice video man!
@amsuprith
@amsuprith Год назад
Thank you so much! Great explination...
@SagarSundriyal
@SagarSundriyal 2 месяца назад
good one
@jayantmishra6897
@jayantmishra6897 Год назад
tree question are very easy after watching your lecture. thanks bhayia
@mounishgoud8417
@mounishgoud8417 2 года назад
Crystal clear explanation !!
@Shiru99_
@Shiru99_ 2 года назад
What if tree contains only one node (I mean other node doesn't belong to the tree). Still this algo will provide an ancestor :(
@debabratabhakat3828
@debabratabhakat3828 2 года назад
I also had same doubt. Probably keep a pair while traversing to check if both the nodes were found or not.
@rajasekaranp7322
@rajasekaranp7322 Год назад
Check the leetcode question constraint. P and Q will exist in the tree.
@purubhargava8096
@purubhargava8096 Год назад
Lode 😂
@nihalnandannayak8869
@nihalnandannayak8869 Год назад
This will be a invalid test case.
@Pirates571
@Pirates571 Год назад
It contains at least 2 nodes
@14-a-akritiawasthi35
@14-a-akritiawasthi35 7 месяцев назад
We learn from u bhaiya♥️
@user-lm8lu2yh1b
@user-lm8lu2yh1b Год назад
striver sir you are op what is extreme level solution 😍😍😍😍well this is my first comment in your channel because you do a very good job
@rashikakurhade3499
@rashikakurhade3499 Год назад
Very nice explanation. Thank you.
@snehabaser3155
@snehabaser3155 2 года назад
Next level explaination💯
@MohanaKrishnaVH
@MohanaKrishnaVH 2 года назад
Awesome Explanation! Understood.
@sushmitakumari8252
@sushmitakumari8252 Год назад
you got new subscriber . outstanding explanation !🙂
@abhinanda7049
@abhinanda7049 Месяц назад
understood
@rekhaagarwal7224
@rekhaagarwal7224 2 года назад
One of the best dry run done ever
@shivalikagupta3433
@shivalikagupta3433 2 года назад
Thank you :)))) Was nicely explained.
@amintalukder7189
@amintalukder7189 9 месяцев назад
You are rock bhaia Jee
@vinayjadon7840
@vinayjadon7840 2 года назад
@10:08 you returned when you found 8, but what if 7 is present in 8's subtree, that is not explored?
@takeUforward
@takeUforward 2 года назад
Then 8 will only be the lca na even if 7 is under subtree. So why to go deep
@renukasubramaniyam754
@renukasubramaniyam754 2 года назад
What if 7 is not present in the tree at all
@vinayjadon7840
@vinayjadon7840 2 года назад
@@renukasubramaniyam754 I think it was mentioned in question that both nodes are present. However, even if it's not mentioned, we can have 2 flags found1 and found2, and iterate once to see if both are present. And if anyone or both are not present, we can return null without performing actual logic.
@your_name96
@your_name96 2 года назад
@@takeUforward hey then if the question comes likes print the path from one node to the other one including the lca (which will be a distinct path) this approach would not work right? then the brute force approach is needed right?
@lifehustlers164
@lifehustlers164 10 месяцев назад
Completed 28/54 (51%) done!!!
@shashikantmony7844
@shashikantmony7844 2 года назад
Really loved the explanation!
@manojjain3501
@manojjain3501 2 года назад
Commenting to increase count +1 , Nice collection of videos.
@adrishbhattacharya508
@adrishbhattacharya508 Год назад
Great explanation!
@nileshsinha7869
@nileshsinha7869 2 года назад
what an explanation 🙌
@harshit4190
@harshit4190 2 года назад
how many more videos left in tree series? Eagerly waiting for DP series.
@ayushpatel4475
@ayushpatel4475 Год назад
Overwhelming explanation 👏👏👏👏 bhaiya 🥳🥳🥳
@vivekparashar...8716
@vivekparashar...8716 2 года назад
nice bro keep it up you are our motivation😎😎😎
@atjhamit
@atjhamit 2 года назад
Hi, thanks for the video. One query though : what is one of the nodes is not in the tree at all? It will incorrectly return the node which is!
@sakshisrivastava4265
@sakshisrivastava4265 Год назад
After so many days....yayyyy I could solve a ques all on my own and on first try...dayumn..Ik it's not a big deal but it's a good milestone for me
@user-yt4vb8ii2f
@user-yt4vb8ii2f 28 дней назад
hey striver, I really like ur videos because of the clarity with whick you teach. However, this video lacked clarity, as i wasnt convinced why would that case work where lca(x, y) is x. However it worked, and after doing some dry runs i understood why it worked but you didnt cover this case in the examples. Just a positive feedback 😄
@sudeepbattu5525
@sudeepbattu5525 4 месяца назад
Hi Striver, I think in the brute force technique the space complexity is O(Height of the tree) am i right ?
@user-qt3kr1vx4c
@user-qt3kr1vx4c Месяц назад
but why don't we return or break the program as soon as we get lca for two nodes
@nagavedareddy5891
@nagavedareddy5891 2 года назад
Huge respect...❤👏
@aswithasai4015
@aswithasai4015 Год назад
what if the p is a root and q is a node in the branch of p
@sreeharianilkumar1
@sreeharianilkumar1 2 года назад
What if node 7 was the left node of node 8 ? @ 10:00
@takeUforward
@takeUforward 2 года назад
If you got 7 you return
@AbhishekKumar-vr7sh
@AbhishekKumar-vr7sh 2 года назад
As soon as node 8 is encountered, it returns its value to the parent node and we don't even need to check for 7 bcoz in that case 7 will lie in the subtree rooted at node 8.
@godlevelchoker4543
@godlevelchoker4543 Год назад
thank you , you helped a lot
@amarpreetkaurrekhi71
@amarpreetkaurrekhi71 11 месяцев назад
very nicely explained
@blitzkrieg5454
@blitzkrieg5454 2 года назад
ohhh bhaiiiiii, behtreeen solution hai
@sonalitribhuvan3409
@sonalitribhuvan3409 Год назад
Awesome Explaination..
@RanveerAllhabadia
@RanveerAllhabadia Год назад
Nice explaination!
@666Imaginative
@666Imaginative 2 года назад
thanks man .... God bless you
@Harish-ne1lh
@Harish-ne1lh 2 года назад
hi Striver thanks for the superb explanation as always! what device/tool do you use for your examples? some tips for taking whiteboarding interviews from home would be nice :)
@rajakunalpandit3594
@rajakunalpandit3594 Год назад
what will happen in the case of skew tree? What if a node doesn't have it's left node and it's right node is the required node and the node itself is the required node. Then how this solution work in that case?
@mohammadtalha360
@mohammadtalha360 2 дня назад
what when one of the value is not present in tree
@abc-ym4zs
@abc-ym4zs Год назад
bhaiya just watching 4 min video i got accepted solution in leetcode simply hatsoff bhaiya i dont even think i can solve this question
@coding8453
@coding8453 2 года назад
Beautiful Explanation 😍😍
@GeneralistDev
@GeneralistDev Год назад
Superb explanation!
@herculean6748
@herculean6748 Год назад
Great explantion :)
@utkarshsharma6650
@utkarshsharma6650 2 года назад
understoooood. thanks a lot :)
Далее
L28. Maximum Width of Binary Tree | C++ | Java
22:41
Просмотров 220 тыс.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Ummmm We "HAIR" You!
00:59
Просмотров 3,1 млн
5.5 Math Books For Self Made Mathematicians
25:50
Ummmm We "HAIR" You!
00:59
Просмотров 3,1 млн