Lowest Common Ancestor Binary Tree

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

КОМЕНТАРІ • 337

  • @solflare101
    @solflare101 17 днів тому +2

    came here after trying to read and failing to understand the leetcode editorial on this question. this was a fantastic explanation, thank you.

  • @cheofusi3562
    @cheofusi3562 4 роки тому +69

    Recursion is indeed a divine art

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

      It is easy to go through, and everything is so nice, besides if the binary tree contains Integer.MAX_VALUE layer, for example, the call stack may be passing away.

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

      you probably dont give a damn but does any of you know of a way to log back into an Instagram account??
      I was stupid lost the login password. I would love any tips you can give me

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

      @Kylan Ali instablaster =)

  • @ok123ut
    @ok123ut 4 роки тому +30

    the way this was explained in 11 min. I don't think i can find more valuable solutions for this in such a short time anywhere else. Amazing!

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

    After i get tired of the logics and code explained by everyone, i do watch your video to understand it in layman and practical way.

  • @xuwang3253
    @xuwang3253 5 років тому +12

    I love this guy's multiple walking-through examples on white board!

  • @Aksionzapion
    @Aksionzapion 8 років тому +9

    The space complexity of both the algorithms is O(height), because the recursive algorithm will have function calls on the stack.

  • @kevinbaijnath6974
    @kevinbaijnath6974 7 років тому +16

    Wow, great explanation about the algorithm! I appreciated the fact that you gave multiple examples that tested different things!

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

    Best Video on LCA available on UA-cam, Thanks Tushar!

  • @robinsoni4778
    @robinsoni4778 4 роки тому +15

    The other solution also takes the implicit stack during recursion, so yes it does require the extra space.

  • @guru007pavan
    @guru007pavan 5 років тому +13

    Too good explanation. short and sweet. I can say this particular solution is way better explained than Back ToBack SWE. Thanks and appreciate your effort...

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

    Optimization note, if the left subtree search yielded the LCA, there's no need to search the right subtree. This can only be avoided by keeping track of how many of the target nodes have been found; it's not sufficient to check if the left subtree search returned a node that is not one of the target nodes, because one of the target nodes may as well be the LCA. For example, 6, and 2.

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

      ASSUMTION:
      We may assume that either both n1 and n2 are present in the tree or none of them are present.

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

      NOTE : optimisation not works for special case

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

    Thank you for covering multiple cases. Other videos didn’t explain as thoroughly as you and didn’t go through many test cases

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

    This is a very useful, well explained, and simple algorithm. Thank you, Tushar.

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

    Thank you! Finally a video that helped me understand the recursive details of the various cases of binary tree

  • @dnl_blkv
    @dnl_blkv 7 років тому +16

    Another great explanation with a beautiful solution!

  • @depression_plusplus6120
    @depression_plusplus6120 3 роки тому +25

    After 5 years he's still helping

  • @dianel.344
    @dianel.344 8 років тому +13

    Thank you, sir! I was confused about this recursive code, but now I understand how it works perfectly!

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

    Last example is really important to explain both nodes in the same path.

  • @leonlew1386
    @leonlew1386 8 років тому +2

    This was a great visual walkthrough. Clear and concise.

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

    Nicely explained. This is a popular problem statement in Amazon interviews.

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

    Excellent video/explanation. Your videos make algorithms so much easier.

  • @cachegrk
    @cachegrk 8 років тому +2

    You are videos are just awesome! Great job! Can't imagine prep without your videos!

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

    Great job Tushar! Absolutely awesome walkthrough..

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

    Six years later and im still learning from you

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

    The recursive approach uses far more space than finding the paths to the nodes. In terms of space efficiency the approach taken in the first two minutes is actually more efficient!

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

    Your explanation always hits the spot. Thanks :)

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

    man, your hair style and explanation a true entertainer!!

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

      Hahahaha !!! He’s cool tho

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

    Thank you sir for this dry run feeling lucky to find this video ... Keep making such dry run video sir Thank you

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

    Thanks for the great explanation

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

    hi Thushar, so nice of you...explained very well

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

    thank you so much this is the most helpful video ive found for this question

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

    Clear and straight to the point.

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

    great explanation! this dry run really helped me a lot

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

    Excellence! Real knowledge, thank you.

  • @nimishbajaj3815
    @nimishbajaj3815 8 років тому +2

    Great work, as you recommended I started solving problems on GeeksForGeeks, your videos + that website together make up a great learning experience thanks again, keep up the good work !

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

    In the recursive solution isn't anyway space is consumed due to stacks

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

      yes, obviously .. space complexity is O( h ) .. worst case will occur when the tree is skewed and the ancestor lies beneath of it.

  • @antuancaraballo9691
    @antuancaraballo9691 8 років тому +3

    Love your explanations Tushar! You are awesome!

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

    Recursion Explained nicely, thanks

  • @chrisy.703
    @chrisy.703 2 роки тому

    best lca video in youtube so far!

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

    Great explanation as usual!

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

    I was asked this question in an interview, with 2 special conditions as the follow-up:
    1. The given 2 TreeNodes are NOT guaranteed to be on the tree.
    2. If either or neither of them is on the tree, it is required to return null.

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

      I can do that in n^2. whats your approach?

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

      @@harshsahu7825 that's pretty bad then. The worst algorithm I can think of just at the top of my head is to search the tree for the first node n1, then for the second one n2 and if either one wasn't found, then return null. If both were found, run the same algorithm that was explained in this video. In total, this algorithm has time complexity of O(n+n+n)=O(n). It could definitely be optimised

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

      @@agfd5659 he is just a bad teacher lol, realized a bit later

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

    Thank you so much for your contribution..I think it is one of the best lectures i have ever seen for like this focusing on interview problems alone..Again thank you so much...please keep on share more and more challenging problems

  • @14rucha
    @14rucha 8 років тому +1

    Awesome video! Your explanation is too good. I can understand recursion very easily through your video.

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

    great explanation, you have high-quality videos..thanks.

  • @AP-eh6gr
    @AP-eh6gr 8 років тому +104

    in the last 8,7 example, is there an assumption that both given nodes whose ancestor we are looking for, have to be present in the tree?
    bcoz we returned 8, and never went down to 7 to see if it was actually there or not

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

      I think we should make assumptions clear that is both nodes should exist and nodes are not equal, tree with one node etc?
      static Node lca(Node rootNode, int a, int b, AtomicBoolean found) {
      if (rootNode == null) {
      return null;
      }
      if (found.get()) {
      return null;
      }
      Node left = lca(rootNode.left, a, b, found);
      Node right = lca(rootNode.right, a, b, found);
      if (left != null && right != null) {
      found.set(true);
      return rootNode;
      }
      final boolean rootMatched = rootNode.i == a || rootNode.i == b;
      if (rootMatched) {
      if (left != null || right != null || a == b) {
      found.set(rootMatched);
      }
      return rootNode;
      }
      if (left != null) {
      return left;
      } else if (right != null) {
      return right;
      } else {
      return null;
      }
      }
      This should work for all the cases. I used AtomicBoolean but can be replaced by MutableBoolean.
      You have a match only when found returns true.

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

      I saw the solution to this problem over gfg but couldn't get the part of searching even after we were using maps for given 2 values... thnx for your question.. helped me alot

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

      Even if we traverse until node 7, it would eventually return the same value 8 to the root of the tree. This case holds true every time when one of the nodes is a ancestor.

    • @abhinavmishra7617
      @abhinavmishra7617 4 роки тому +4

      this algo is based ln the assumption that that both nodes will be present in the tree...nice observation btw

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

      4 years ago....damn

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

    Very nice explanation with the examples!

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

    It's much clear now. Thanks a lot for your explanation.

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

    Amazing explanation!!!

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

    Awsome Explanation Bro!!

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

    Very lucid explanation

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

    Your solutions are amazing!! Keep doing it :)

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

    Excellent explanation! Hats off!

  • @RoshanKumar-nx6rk
    @RoshanKumar-nx6rk 3 роки тому +1

    Your second algorithm has also O(n) space complexity!!! You can't neglect the function stack calls.

  • @shreyasingh-sn4bs
    @shreyasingh-sn4bs 7 років тому +2

    I have become a fan! Great work Sir :)

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

    Very well explained. Small correction required in your code, instead of doing nodes equals comparison using '==', you need to do node data comparison as shown below.
    if(root.data == n1.data || root.data == n2.data){
    return root;
    }

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

      That doesn't need to be corrected. The value is irrelevant. Node n1 and n2 hold the address of the nodes that need to be found. All you need to do is compare the address.

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

    Genius approach...well explained

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

    Nice explanation sir...really good video

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

    Thank you so much, Tushar!!

  • @harshitpruthi5744
    @harshitpruthi5744 4 роки тому +8

    I think the method you explained above is based on the assumption that both n1 and n2 are present
    Can you please explain what if one of the two or both nodes aren't present in Binary tree
    Thanks in Advance

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

      its given in the question that both n1 and n2 will always be there in the tree.

  • @rohitkumar-yz5qy
    @rohitkumar-yz5qy 6 років тому +1

    you have given best explanation..thanks a lot

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

    Very nicely explained! Thanks.

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

    Really really helpful.

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

    amazing!! Thanks Tushar! PLease continue!

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

    above & beyond awesomeness!

  • @vuleenguyen
    @vuleenguyen 5 років тому +2

    Thanks a lot. You gave me the idea to solve this problem

  • @HieuLe-mh4bc
    @HieuLe-mh4bc 3 роки тому

    Great explanation! Thank you for the video.

  • @444not
    @444not 3 роки тому

    Thank you for the explanation. Very helpful.

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

    Great job, the explanation is very clear and lucid. Thanks a lot :).

  • @bumbarumbado
    @bumbarumbado 8 років тому +1

    beautiful explanation!

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

    Here we assume that both nodes are present. If one of them is not present, we return a wrong output.

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

    ek like to banta hain, solid explanation hain

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

    I checked various sites, even during interviews of big companies & everywhere the same kind of solution is given & I have following issues with this problem & I wonder that why people don't raise this concern, either they don't understand English or they are just interested in clearing the interviews to get the money -
    a) How can you assume that both nodes are present in the tree without saying it anywhere.
    b) Because above assumption is missing then you might be returning wrong answer even if there is not common ancestor, rather we should say that one or both the given nodes not found.
    c) When you use some other language's word in your problems then respect the meaning of that word also or don't use that word at all. How can I be my own ancestor in any condition, so how can 8 be its own ancestor. So if you have different definition then use different word also, say like find the common meeting point etc. But using the word 'Ancestor' here is not right.
    Improvement - If we follow the correct definition of Ancestor then we can apply the same solution to find the common ancestor for multiple nodes. Assumption : All nodes in the tree are unique.

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

    Very nice explanation thank you sir

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

    Very nice Explanation.

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

    Problem is what happens if only one of the given nodes is present and other is missing

  • @jaspertienny8976
    @jaspertienny8976 8 років тому +1

    The amazing Tushar. Thanks!

  • @manishbhatt3614
    @manishbhatt3614 8 років тому

    @Tushar: Good work and good explanations.

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

    Genius. Thank you very much.

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

    finally good explanation. I understand it now

  • @ВолнистоеМасло
    @ВолнистоеМасло 6 років тому

    Tushar is the best!

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

    Excellent Explaination

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

    Thank you for the video. One feedback I have is that the mic is too hard for the ears

  • @0xeb-
    @0xeb- 3 роки тому

    Perfect. Thank you.

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

    Great videos dude. Thanks!

  • @rajusaratkar2599
    @rajusaratkar2599 8 років тому +2

    Very nice and Clear Explanation ..Thanks for the Video.

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

    Great explanation! Thank you.!

  • @DanielLee-et4sk
    @DanielLee-et4sk 4 роки тому

    Awesome Explanation!

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

    Great explanation, Thanks a lot

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

    i really love this guy

  • @mehrdadk.6816
    @mehrdadk.6816 4 роки тому +1

    complexity can be O(logn) since it is a binary tree

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

    Thank you . Good one . You are awesome. from 10.55 the way you talked, looks like u are iterating an array ['like', 'share', 'subscibe'] + 'this video'

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

    Thanks for the video, really helpful

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

    In this algorith the 2nd last line "if(left==NULL && right==NULL) return NULL;" is not required as last line will return NULL if both are NULL.

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

    Nice explanation, thank you sir.

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

    God bless you man!

  • @iamyaqoob
    @iamyaqoob 8 років тому +2

    Wow! Great explanation!

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

    I think the command wriiten in 3rd line should be after 5th line.This would cover all the test cases and we would not be needed to make any assumptions.

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

    Thank you very much.....! Super solution!!!

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

    which is better this approach or binary lifting?

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

    won't this solution will fail for a skewed tree where one node does not exist. for example LCA(3,8) in this tree (null denoted by #) :
    1
    /\
    # 2
    /\
    # 3
    /\
    # 4
    Expected output: null
    Actual output : 3