Lowest common ancestor of two nodes in Binary Tree Algorithm

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

КОМЕНТАРІ • 136

  • @Kaushikvel
    @Kaushikvel 7 років тому +116

    Some of the best things about your video,
    1. your slow explanation.
    2. code walk through
    3. Complete explanation with lots of examples.
    Thank you.

  • @tanmayagarwal8513
    @tanmayagarwal8513 3 роки тому +23

    OKK .. lets just appreciate his innocent smile!

  • @vardaanbajaj3181
    @vardaanbajaj3181 6 років тому +23

    This topic has confused me since 2 days. This is the best explanation I've found. Thank you sir :) Cleared all my doubts :)

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

    Absolutely love the clear explanation and walkthrough. Thank you!

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

    Sir ji, apka teaching ka FAN ho gya hu me to .. love you.
    Some of the best things about your video,
    1. your slow explanation.
    2. code walk through
    3. Complete explanation with lots of examples.

  • @ivantishchenko4686
    @ivantishchenko4686 4 роки тому +7

    The author is a genius. Thank you very much!

  • @uncletom321
    @uncletom321 5 років тому +3

    I rarely subscribe to channels, but I did for yours because of how great your teaching method is. It has really helped me better understand data structures and algorithms. Thanks!

  • @aishwaryadwani9365
    @aishwaryadwani9365 5 років тому +1

    Sir one thing i must say here , your videos and explanations are out of the box. Very easily anyone can get it. Thanks allot.

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

    i was not able to understand this question's solution from any other video but your simple explanation worked and i will never forget this solution again, thanks so much sir!

  • @sushmanthnatha4019
    @sushmanthnatha4019 4 роки тому +1

    Sir, I have watched many other people videos but your's are simply crystal clear

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

    usually i have a hard and long time understanding these kinds of videos, but your videos are so clear I feel like even a toddler can understand

  • @bajracha
    @bajracha 5 років тому

    Thank you so much for such a clear explanation. Your explanation not only taught me how to understand walking through the algorithm but it actually taught me how to think about a solution and how to approach the solution. Thanks again.

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

    Hello, Thanks for explaining so well, In your logic for finding out LCA works fine if both the nodes are present and both the nodes are part of different sub tree. Two situation does not handle in this code. 1) if either of the node is not present in tree itself 2) if second node is part of subtree of first node. for exm, P and L nodes. If user enters these two nodes then this algorithm will not work.
    Solution algorithm:
    1) Both the nodes must present in tree otherwise print error and return.
    2) if left and right returns non NULL, this is LCA. Print LCA and return NULL.
    3) if second node is in subtree of first node then only first node we will return till root node. in such case main function shall have a piece of code, if final return is non NULL then this is the LCA, print LCA.
    I can post the code if someone needs. thanks

  • @ishanpand3y
    @ishanpand3y 4 роки тому +21

    Sir, I think this is preorder traversal. Because in inorder traversal first we go left then node then right, while in preorder traversal first we go node then left and then right.

    • @marioburgos8656
      @marioburgos8656 4 роки тому +1

      I agree

    • @cripz4203
      @cripz4203 4 роки тому +7

      isnt it postorder as we are processing what to return after left and right.

    • @utkarshsingh4456
      @utkarshsingh4456 4 роки тому +1

      @@cripz4203 postorder hai bhai, you are right.

    • @bismeetsingh352
      @bismeetsingh352 4 роки тому

      It is inorder since we go leftmost,root and then right

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

      No...its postorder.

  • @YSSP4
    @YSSP4 6 років тому

    Awesome video. Your explanations are simple and clear to understand. Please keep up the good work.
    For others, just like me if you are bothered about corner case where one of the element is not present in the tree, then try postorder traversal instead of inorder traversal so that you look in to both left and right nodes before coming to root node.

  • @adaz2724
    @adaz2724 4 роки тому +2

    I love this guy, very clear explanation !!!

  • @user-uh4be8ci7i
    @user-uh4be8ci7i 2 роки тому

    You are the best teacher sir thank you so much for all this solutions

  • @RavinderSingh-nh6th
    @RavinderSingh-nh6th 5 років тому +2

    i dont know how to praise you. i have less words to appreciate you..

  • @shashwatagrawal8412
    @shashwatagrawal8412 5 років тому +1

    Amazing explanation. Please make more videos on Algorithms.

  • @daspradeep
    @daspradeep 6 років тому +6

    good explanations, got tripped by the edge case a bit because this assumes both nodes to be present in the tree, which is fine i guess. In case one of the nodes is not there then it fails.

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

    thanks for making things clear and simpler sir

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

    sir this is a very good explanation, just one point that you should have told that we are taking the assumption that both the nodes exist in the tree

  • @hritikagarwal7676
    @hritikagarwal7676 4 роки тому

    It would be far better if you also explain the intuition to this solution. Knowing the algorithm makes half of the work but knowing what led to this algorithm will make the solution video totally worthy.

  • @sampathmethuku7428
    @sampathmethuku7428 5 років тому +1

    very good explanation , but I think if the any one node either p or q does not exists then your code will fail, we expect to return null as one node is not present in tree.
    but your code returns the existing value.

  • @shwetadk1986
    @shwetadk1986 5 років тому +1

    You are simply amazing !. Keep the good work and spread the knowledge

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

    No need for "else". Great code walkthrough and explanation !

  • @dipakkumarsinha5811
    @dipakkumarsinha5811 4 роки тому

    Bahut badhiya sir .... Maja a Gaya sir

  • @anty_07
    @anty_07 5 років тому

    A somewhat concise solution which uses the property of BST - LCA's value WILL fall between the the two given nodes. SO you keep going left from root till both the nodes values are less than current node , and keep going right till both value are greater than current value. Below is the code.
    while(root.data < v1 && root.data < v2){
    root = root.right;
    }
    while(root.data > v2 && root.data > v1){
    root=root.left;
    }
    return root;

    • @vm1662
      @vm1662 5 років тому

      Yes this works perfectly for Binary Search Tree but I guess the code explained in the video is for Binary Tree :)

  • @gouravsharma2755
    @gouravsharma2755 6 років тому

    Very good explanation.I liked the reasoning in your videos.

  • @nishantprajapati7166
    @nishantprajapati7166 5 років тому +1

    Awesome explanation, great sir.

  • @shadesofspice5315
    @shadesofspice5315 4 роки тому

    Clear explanation. Easy to understand

  • @HoanNguyen-fc8vb
    @HoanNguyen-fc8vb 3 роки тому +1

    Thank you for your tutorial. You are one of the best so far. For the if(left !=null && right = null) return root. Is that right or (right !=null) .Please explain. Thank you very much.

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

    Great Video. Thank you sir. What happens in the case when there is only one value present in the tree, and the other value is not. In that case, the algorithm is not working.

  • @Sudarshansridhar
    @Sudarshansridhar 5 років тому

    what if the one of node given to find lca is not present in the tree?
    i think this solution holds good for both values are present. (if i am not wrong)

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

    really good method of explaining!!

  • @abhishekkumargupta3043
    @abhishekkumargupta3043 4 роки тому +1

    This man is awesome. Thank you.

  • @angadrajsingh4311
    @angadrajsingh4311 4 роки тому

    Sir amazing explanation

  • @swj_69420
    @swj_69420 4 роки тому +1

    Can you please tell how is this inorder? Shouldn't it be preorder

  • @4yt158
    @4yt158 4 роки тому +1

    Your explanation is awesome bro! Thank you! :)

  • @司雨-w6b
    @司雨-w6b 2 роки тому

    so clear explanation!

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

    try this approach
    struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {

    if (p->valval && q->valval)
    return lowestCommonAncestor(root->left,p,q);
    if (p->val>root->val && q->val>root->val)
    return lowestCommonAncestor(root->right,p,q);
    return root;
    }

  • @PIYUSH-lz1zq
    @PIYUSH-lz1zq 2 роки тому

    DAMM !!! ABSOLUTLY SPOT ON

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

    Ur a amazing teacher

  • @kartikaygoel3042
    @kartikaygoel3042 4 роки тому

    Great Video...
    PS-: can watch it at 4x comfortably

  • @danielshalam2258
    @danielshalam2258 6 років тому +1

    finally i understand how it works ! thank you very much !

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

    Awesome video. Great explanation, keep up the good work sir!!

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

    I think so this algorithm will fail when there are multiple occurrences of n1 and n2, @8:06 pause the video see the tree, and replace the following nodes:
    *h with m,
    i with r,
    e with r.*
    after first finding m and r, node "D" becomes LCA and returns itself to "B", then "B" checks on its right, it finds "R", now on left of "B" we have "D" as LCA and on right of "B" we have "R" as LCA, so it will return "B" as LCA which is wrong, LCA Should have been "D" only.

  • @alokdeshpande5517
    @alokdeshpande5517 4 роки тому

    Excellent explanation 👍

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

    This solution not work when one of the two nodes is found and not the second one. So its return the founded node.

  • @natesh1
    @natesh1 6 років тому +1

    Awesome vids, can u please consider categorizing ur vids into playlists, for new watchers it helps a lot, otherwise they would have to keep scrolling all ur vids.

  • @payalsagar1808
    @payalsagar1808 4 роки тому +1

    the best!☺

  • @aparna123pathak
    @aparna123pathak 6 років тому

    No doubt in awesomeness of explanation!!

  • @1388tushr
    @1388tushr 5 років тому +5

    How about LCA of "f" and "j"? I think once the code hits "f", it will return "f", it won't go to its child.

  • @radhakantaghosh7295
    @radhakantaghosh7295 6 років тому +3

    Hi, Does this method will work for "d" and "h" ? ..........what i am thinking is once execution hit "d" then, it will return that node and will never visit "h".

    • @raniajay0410
      @raniajay0410 6 років тому +1

      whats the use of visiting h if we have already found d which is LCA.

    • @1388tushr
      @1388tushr 5 років тому

      @@raniajay0410 then how will you know whether "h" exists or not?

    • @abcd1235911
      @abcd1235911 5 років тому

      @@1388tushr Exactly. If one of the nodes is not present this algorithm will return the other node which is present

    • @RohanSingh-bl5ho
      @RohanSingh-bl5ho 5 років тому +1

      @@abcd1235911 this what i was thinking while i was watching this video, this algo is not completely correct

  • @rohinirt6362
    @rohinirt6362 5 років тому

    Thank you so much for all your video sir...

  • @thecreative9102
    @thecreative9102 4 роки тому

    Thank you so much for great explanation

  • @7Critics
    @7Critics 5 років тому

    Great explanation!

  • @nikhilkumarmishra1225
    @nikhilkumarmishra1225 5 років тому +1

    You are godsent, thanks a lot!

  • @unboxingzindagi9972
    @unboxingzindagi9972 4 роки тому

    Love you bro. You are so real!!

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

    nice video.............................

  • @lokeshnegi5051
    @lokeshnegi5051 4 роки тому

    well explained..

  • @neetisharma3768
    @neetisharma3768 5 років тому +1

    Liked and subscribed :) Thank u for explaination

  • @rajnikushwaha1459
    @rajnikushwaha1459 6 років тому

    sir your video is really awesome

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

    Thanku ji

  • @anupkmr03
    @anupkmr03 5 років тому

    Nice explanation Thank you.

  • @borisa6952
    @borisa6952 7 років тому

    Thank you for the explanations. I would like to know how to compute and write the algorithm of the "distance between the node e and node i" in this binary tree.

    • @borisa6952
      @borisa6952 7 років тому

      I mean how to write the algorithm between two nodes (not root node) in a binary. The example with nodes e and i would be useful for me. Thank you in advance.

  • @vivekmit
    @vivekmit 5 років тому

    Good explanation

  • @sayalishelke9597
    @sayalishelke9597 4 роки тому

    Best explanantion :) .Subscribed

  • @VenkatGonu
    @VenkatGonu 4 роки тому

    code doesn't work if one of the node is not present, ideally it should return null but it returns the other node which is found

  • @kabboghosh1853
    @kabboghosh1853 5 років тому

    best teacher

  • @sumitkumar-wp4xd
    @sumitkumar-wp4xd 7 років тому

    great job sir

  • @jagritbhupal5836
    @jagritbhupal5836 4 роки тому

    Thank you

  • @abhishekkarn8918
    @abhishekkarn8918 6 років тому +2

    this is preorder traversal na sir?

  • @TS-ku2lg
    @TS-ku2lg 4 роки тому

    Thank you so much sir!

  • @oneworldofstem7724
    @oneworldofstem7724 4 роки тому

    I wonder when you first encounter this question, how do you figure out the possible steps for getting the answer? I am having trouble of algorithm questions recently. Very hard for me to think of the answer

  • @arpitverma8060
    @arpitverma8060 4 роки тому

    VERY WELL EXPLAINED||

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

    great explanation but i think this is pre order traversal

  • @AshokBathini
    @AshokBathini 7 років тому +1

    If one of the nodes p or q does not exist in the Binary Tree, this function will still return the node which is found, but it should have returned NULL. Am I right?

    • @vivekanandkhyade
      @vivekanandkhyade  7 років тому +1

      yes Ashok , u r right.....Due to the restriction of space on board , I have just focused on the main condition.....in the code we can modify for this corner condition.....Thanks for helping me get better...!

    • @AshokBathini
      @AshokBathini 7 років тому

      It's just a corner case, but otherwise you've explained it very well..good job!

  • @tassda2787
    @tassda2787 4 роки тому

    merci monsieur

  • @sakshamagarwal6852
    @sakshamagarwal6852 5 років тому

    good explanation sir, thanks :)

  • @jamesqiu6715
    @jamesqiu6715 7 років тому +5

    you used postorder traversal ... I think

    • @samaryadav7208
      @samaryadav7208 7 років тому

      yeah because he is returning after checking the values of both the children

    • @gyanasahu1006
      @gyanasahu1006 6 років тому +1

      It is Inorder traversal, as we first check with the current node and return if it is equal to either one. If not equal we expand search to left subtree and right subtree

    • @badsum
      @badsum 6 років тому +2

      Actual result comparison happens after both, left and right, return. It is post order. Also, if checking current node first for the result comparison, it should be pre-order, not in-order.

    • @charismatic1516
      @charismatic1516 4 роки тому

      @@badsum Actually, there is both pre and post happening. However, in terms of logic, we check for LCA condition for the current node before checking it left and right subtrees, hence pre. We also do some checking/processing after the children processing.
      Similar example is when we want to do a sum of all root to leaf paths. In the recursive function, we first add node val to sum so far, then check if we reached a leaf (pre) then return sum, else get sums from left and right child, then add and return those sums (some post).

    • @charismatic1516
      @charismatic1516 4 роки тому

      @@gyanasahu1006 You meant pre, not in

  • @sunnyjain630
    @sunnyjain630 6 років тому +1

    i think u have used preorder traversal!!

  • @pradeepsingh-cg8iv
    @pradeepsingh-cg8iv 4 роки тому

    Thanks bro

  • @SaurabhSingh-ch6nc
    @SaurabhSingh-ch6nc 5 років тому

    Love it ..!

  • @ayushthakur733
    @ayushthakur733 4 роки тому +1

    Explain it for (j,c).... 🤨

  • @mdsaif4696
    @mdsaif4696 7 років тому

    In my interview, the question asked me to return int value.. not node value.. this method just messed.up.
    pls explain what to do if the function demands returning int value

    • @ShivangiSingh-wc3gk
      @ShivangiSingh-wc3gk 6 років тому +1

      You should have just returned node.value and kept something like -1 for a case where you dont find the node

    • @ShubhamKumar-oh3jt
      @ShubhamKumar-oh3jt 5 років тому

      when you are returning the value use .data or .key with the calling function

  • @TechnicalBaniya
    @TechnicalBaniya 7 років тому

    sir for node k the ancestors are f,c,a and the ancestors of node f are c,a then the common ancestor should be c of nodes k and f but you said the common ancestor is f ?

    • @vivekanandkhyade
      @vivekanandkhyade  7 років тому

      the lowest common ancestor for parent and its child is the parent itself. I am sorry i have not explained this in the video. I will reply tomorrow again with a more convincing proof. Thanks.

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

    Should be pre-order instead of in-order.

  • @ricardosmith3752
    @ricardosmith3752 5 років тому

    What if one of the element is in the left branch of other ?

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

    this solution will not work in case if B==root->node ans c is not present

  • @ruchirai5775
    @ruchirai5775 4 роки тому

    nice !!

  • @SaurabhSingh-ch6nc
    @SaurabhSingh-ch6nc 4 роки тому

    this is how the DSA faculty looks like!

  • @prajakta_patil
    @prajakta_patil 5 років тому

    Thank u

  • @ayushthakur733
    @ayushthakur733 4 роки тому

    What if the root node is one of the two node ??

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

    This won't work when one of the two nodes is not found.

  • @hellochii1675
    @hellochii1675 5 років тому

    10:08, I think you want to write "a", but not "LCA" ?

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

    It's good

  • @bigjforever
    @bigjforever 7 років тому

    good. but a little bit slow. I need to see ur vdos at 2x speed

  • @zeref6437
    @zeref6437 5 років тому

    if LCA is not present it will return wrong answer.

  • @ridimamittal4064
    @ridimamittal4064 4 роки тому

    make more videos plzzzzzzzzzzz :(