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

Поділитися
Вставка
  • Опубліковано 25 лис 2024

КОМЕНТАРІ • 308

  • @takeUforward
    @takeUforward  3 роки тому +133

    Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79

    • @rahulsrivastava1040
      @rahulsrivastava1040 3 роки тому +1

      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 роки тому +1

      done bro

    • @ToonTorque
      @ToonTorque 2 роки тому

      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 роки тому +68

    Every other UA-camr 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.

  • @human75788
    @human75788 2 роки тому +73

    I watched about 4 minutes of your video and coded it myself.. Your explanation is just heaven .

    • @als_venky7057
      @als_venky7057 Рік тому +61

      but the real part starts after 4minutes😂

    • @nishankjain88
      @nishankjain88 Рік тому +1

      @@als_venky7057 😂😂

    • @rohanverma3111
      @rohanverma3111 Рік тому +3

      @@als_venky7057 xD 😂😂😂😂

    • @only_for_fun1234r
      @only_for_fun1234r Рік тому +1

      @@als_venky7057 😅😅

    • @SlapB0X
      @SlapB0X Рік тому +7

      that approach should not be done..
      watch the latter half for the optimal approach

  • @surajpalsau870
    @surajpalsau870 Рік тому +15

    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 6 місяців тому

      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 ......

    • @samsingh43
      @samsingh43 6 місяців тому +2

      @@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

  • @vishalgowrav
    @vishalgowrav 2 роки тому +24

    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;
    }
    }
    }

  • @tanyagupta4247
    @tanyagupta4247 2 роки тому +62

    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 роки тому +6

      heyy same, but why are you here then🤔

    • @parthsalat
      @parthsalat 2 роки тому +1

      @@electronx5594 Just to comment this. 😄

  • @imranimmu4714
    @imranimmu4714 Рік тому +2

    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 5 місяців тому

      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

  • @vinaygupta2369
    @vinaygupta2369 Рік тому +24

    Striver bhai rocked.. buddy you are helping thousands of folks like me preparing for DSA interview. :)

  • @ayush52905
    @ayush52905 3 роки тому +4

    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.

  • @_who__knows__16
    @_who__knows__16 3 роки тому +21

    Thanks a lot for contributing to the community.
    Nicely understood!!!

  • @giridharjadala2182
    @giridharjadala2182 2 роки тому +6

    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.

  • @mukitmahmudul2616
    @mukitmahmudul2616 7 місяців тому +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.

  • @kartiksaini5619
    @kartiksaini5619 3 роки тому +36

    The best explantion 🔥🔥🔥🏅 really loved it🔥🔥I must say this is your best video

  • @349_rahulbhattacharya6
    @349_rahulbhattacharya6 3 роки тому +8

    best explanation till date!!Vey very very easily understood as a noob coder.Thanks a lot!!

  • @nelsonoboo5423
    @nelsonoboo5423 Рік тому +1

    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

  • @jajateenandineesahoo259
    @jajateenandineesahoo259 3 роки тому +4

    Never thought that the solution for this question will be so simple and easy to understand.

  • @knowthrvdo
    @knowthrvdo 5 місяців тому +1

    i am solving question by myself without watching lec bcoz of youre awosome lectures thank you keep it up!!

  • @nikhilnagrale
    @nikhilnagrale 3 роки тому +19

    // 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

  • @rushidesai2836
    @rushidesai2836 5 місяців тому +2

    Classic binary tree question! Thanks Striver.

  • @rishabhgupta9846
    @rishabhgupta9846 Рік тому +2

    Understood,able to solve by brute force and with optimized approach after getting a hint.Thank you striver

  • @HoneyComb1711
    @HoneyComb1711 5 місяців тому

    Thank you very much! Striver is the best channel! I refer only to striver videos!

  • @harishsn4866
    @harishsn4866 2 роки тому +3

    Simple and lucid explanation. Thanks, bro.

  • @manasdeora4601
    @manasdeora4601 2 роки тому +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.

  • @surendradas8174
    @surendradas8174 3 роки тому +4

    Wow I was able to write the code myself just after explanation.

  • @Mayanksingh-qp6dy
    @Mayanksingh-qp6dy 3 роки тому +19

    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.

  • @thegreekgoat98
    @thegreekgoat98 2 роки тому +3

    Such a cool teaching... and an awesome logic.

  • @neelpatel122
    @neelpatel122 3 роки тому +4

    Explanation is flawless. keep it up.

  • @ManojKumar-jb4sc
    @ManojKumar-jb4sc 3 роки тому +6

    Nicely explained and easily underatood

  • @ishangujarathi10
    @ishangujarathi10 Рік тому +1

    the optimized approach was awesome, loves the intuition !!! easyily understood

  • @sonukumarpandit9731
    @sonukumarpandit9731 Рік тому +1

    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.

  • @stith_pragya
    @stith_pragya 11 місяців тому +1

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

  • @BTECSPRAKASHSINGH
    @BTECSPRAKASHSINGH 3 роки тому +3

    Striver ,your videos are perfect.

  • @friendsav1244
    @friendsav1244 Рік тому +1

    To save people time, In this video he only explained one case where you will get one element in left side and one in right. but there are also some cases, Consider that we have both the elements in left side of subtree? or there is no element present etc. So this is not the video I was looking for I like to understand every possible case.

  • @ayushpatel2171
    @ayushpatel2171 2 роки тому +11

    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.

  • @manojjain3501
    @manojjain3501 2 роки тому +1

    Commenting to increase count +1 , Nice collection of videos.

  • @snehabaser3155
    @snehabaser3155 3 роки тому +5

    Next level explaination💯

  • @echocoding4550
    @echocoding4550 Рік тому

    u work is really helping us to understand this type of concept. So thank u !!

  • @lifehustlers164
    @lifehustlers164 Рік тому +1

    Completed 28/54 (51%) done!!!

  • @VijayKumar-j4m1b
    @VijayKumar-j4m1b Рік тому

    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

  • @ritikshandilya7075
    @ritikshandilya7075 3 місяці тому

    Thankyou for amazing solution Striver

  • @apmotivationakashparmar722
    @apmotivationakashparmar722 Місяць тому

    Thank you so much Striver !

  • @devanshubilthare5277
    @devanshubilthare5277 3 роки тому +3

    Great Explanation, loving the series so far

  • @jayantmishra6897
    @jayantmishra6897 2 роки тому

    tree question are very easy after watching your lecture. thanks bhayia

  • @uRamPlus
    @uRamPlus 3 роки тому +2

    your on a different level !!! thank you 💎

  • @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

  • @abhaykumarsingh3884
    @abhaykumarsingh3884 2 місяці тому

    Intuition:
    Consider a node as a potential answer (LCA). If both left and right subtrees return non-null values, it means both nodes p and q have been found in different subtrees, confirming that this node is indeed the LCA.
    Now, consider a node that is not the answer. In this case, either the left or right subtree (or both) will return null. However, if one of them is not null, it indicates that one of the nodes (p or q) has been found, and this information will be passed up the tree to potentially contribute to identifying the LCA at a higher level.
    class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root==null || root.val==p.val || root.val==q.val){
    return root;
    }


    TreeNode left= lowestCommonAncestor(root.left,p,q);
    TreeNode right= lowestCommonAncestor(root.right,p,q);

    if(left != null & right != null){
    return root;
    }
    return left != null?left:right;

    }
    }

  • @darkexodus6404
    @darkexodus6404 Рік тому

    I liked this convention more.
    if ( left && right) return root;
    else if ( left) return left;
    else return right;

  • @prabhakaran5542
    @prabhakaran5542 2 місяці тому +1

    Understood ❤

  • @mounishgoud8417
    @mounishgoud8417 2 роки тому +1

    Crystal clear explanation !!

  • @chrisogonas
    @chrisogonas 3 місяці тому

    Well illustrated. Thanks

  • @soumalyadhar.28
    @soumalyadhar.28 3 роки тому +1

    too smooth too good...amazing explanation...thank you STRIVER

  • @pragyapal4258
    @pragyapal4258 2 роки тому +1

    superb explanation!!! it made trees very easy for me. Thank you so much.

  • @dpxy1599
    @dpxy1599 Місяць тому

    faadu bhai faadu

  • @aadeshsharma0001
    @aadeshsharma0001 3 роки тому +2

    now i feel confident in trees by watchng this tree series.

  • @vivekparashar...8716
    @vivekparashar...8716 2 роки тому +2

    nice bro keep it up you are our motivation😎😎😎

  • @MohdMasood-p7n
    @MohdMasood-p7n 5 місяців тому

    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 😄

  • @adrishbhattacharya508
    @adrishbhattacharya508 2 роки тому +1

    Great explanation!

  • @droid-aman
    @droid-aman 6 місяців тому

    thanks bro, your dry run was great,, was struggling to visualize recurssion

  • @harshit4190
    @harshit4190 3 роки тому +3

    how many more videos left in tree series?
    Eagerly waiting for DP series.

  • @nilanjanmajumder8508
    @nilanjanmajumder8508 2 роки тому +2

    great video .... very nicely explained ...... just loved it ❤

  • @shivalikagupta3433
    @shivalikagupta3433 2 роки тому +1

    Thank you :)))) Was nicely explained.

  • @charlesbabbage6786
    @charlesbabbage6786 7 місяців тому

    Beautifully explained!!

  • @rekhaagarwal7224
    @rekhaagarwal7224 2 роки тому

    One of the best dry run done ever

  • @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

  • @ayushpatel4475
    @ayushpatel4475 2 роки тому

    Overwhelming explanation 👏👏👏👏 bhaiya 🥳🥳🥳

  • @rakshayadav1892
    @rakshayadav1892 2 роки тому

    Python code:
    class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
    if not root or root==p or root==q:
    return root
    l=self.lowestCommonAncestor(root.left,p,q)
    r=self.lowestCommonAncestor(root.right,p,q)
    if not l:
    return r
    if not r:
    return l
    return root

  • @roshnisingh7364
    @roshnisingh7364 9 місяців тому

    very well explained !! Thanks

  • @cinime
    @cinime 2 роки тому +1

    Understood! Super amazing explanation as always, thank you very much!!

  • @nagavedareddy5891
    @nagavedareddy5891 2 роки тому +2

    Huge respect...❤👏

  • @_CodeLifeChronicles_
    @_CodeLifeChronicles_ Місяць тому

    this is just perfect

  • @shashikantmony7844
    @shashikantmony7844 2 роки тому +1

    Really loved the explanation!

  • @rashikakurhade3499
    @rashikakurhade3499 2 роки тому

    Very nice explanation. Thank you.

  • @OIAOa
    @OIAOa 9 місяців тому

    crystal clear sir

  • @jinhuang7258
    @jinhuang7258 Рік тому

    You are so good. Thank you!

  • @dipeshsingh2112
    @dipeshsingh2112 2 місяці тому

    Looking at comments I think I am the only one who got another idea apart from this recursive approach. The intuition is to use property of BST. the right of node will contains elements > root and left of nodes will contains elements < root. So you can use this to find the solution iteratively.

    • @vvvvvviiii
      @vvvvvviiii Місяць тому

      its no where written in the question that its a binary search tree

  • @amarpreetkaurrekhi71
    @amarpreetkaurrekhi71 Рік тому

    very nicely explained

  • @sushmitakumari8252
    @sushmitakumari8252 Рік тому

    you got new subscriber . outstanding explanation !🙂

  • @vivekveman4961
    @vivekveman4961 3 роки тому

    Best ever solution for this problem!

  • @2xReturns-FOOTBALL
    @2xReturns-FOOTBALL Рік тому

    beautiful explanation my man.

  • @rushyya
    @rushyya Рік тому

    UNDERSTOOD! THANK YOU🙌

  • @RanveerAllhabadia
    @RanveerAllhabadia Рік тому

    Nice explaination!

  • @mohit7717
    @mohit7717 5 місяців тому +1

    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?

  • @amsuprith
    @amsuprith Рік тому

    Thank you so much! Great explination...

  • @MohanaKrishnaVH
    @MohanaKrishnaVH 2 роки тому

    Awesome Explanation! Understood.

  • @blitzkrieg5454
    @blitzkrieg5454 3 роки тому

    ohhh bhaiiiiii, behtreeen solution hai

  • @SnehithYamalapalli
    @SnehithYamalapalli 2 місяці тому

    Just sooo good

  • @shivangisrivastava1158
    @shivangisrivastava1158 3 роки тому +2

    Totally clear, loving this series. Thanks a ton for making this.❤️

  • @aryansinha1818
    @aryansinha1818 2 роки тому

    It feels like I am sitting in my super confident English teacher class.

  • @DeadPoolx1712
    @DeadPoolx1712 Місяць тому

    UNDERSTOOD;

  • @sonalitribhuvan3409
    @sonalitribhuvan3409 Рік тому

    Awesome Explaination..

  • @prachimatta
    @prachimatta 7 місяців тому

    Excellent

  • @johncenakiwi
    @johncenakiwi 2 роки тому +1

    In this question, we are guaranteed to find p and q as per the problem statement.
    One interesting follow up question is : return null if either p or q or both are not present in the tree.
    Hint : solve it using a Post Order traversal.

  • @GeneralistDev
    @GeneralistDev Рік тому

    Superb explanation!

  • @vinayjadon7840
    @vinayjadon7840 2 роки тому +5

    @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 роки тому +14

      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 роки тому +1

      @@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?

  • @14-a-akritiawasthi35
    @14-a-akritiawasthi35 Рік тому

    We learn from u bhaiya♥️

  • @666Imaginative
    @666Imaginative 2 роки тому

    thanks man .... God bless you

  • @SagarSundriyal
    @SagarSundriyal 7 місяців тому

    good one

  • @fazilshafi8083
    @fazilshafi8083 8 місяців тому

    Thank you! 😇

  • @Shivi32590
    @Shivi32590 4 місяці тому

    thank you

  • @godlevelchoker4543
    @godlevelchoker4543 Рік тому

    thank you , you helped a lot