L47. LCA in Binary Search Tree

Поделиться
HTML-код
  • Опубликовано: 30 сен 2024
  • Entire DSA Course: takeuforward.o...
    Check our Website:
    Linkedin/Instagram/Telegram: linktr.ee/take...
    #treeSeries #striver #placements

Комментарии • 121

  • @takeUforward
    @takeUforward  2 года назад +45

    Please do like and share among your friends!! ^ _ ^

  • @divyansh2212
    @divyansh2212 2 года назад +49

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

  • @sammedpatil3907
    @sammedpatil3907 2 года назад

    nice explanation....

  • @aaluSandwich
    @aaluSandwich 2 года назад +36

    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 года назад +23

      This guy has haters?
      He is an inspiration bro🙂

  • @galleryofjatin19
    @galleryofjatin19 2 года назад +60

    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!

  • @vivekjaiswar6825
    @vivekjaiswar6825 2 года назад +14

    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?

  • @priyankasetiya1358
    @priyankasetiya1358 3 месяца назад +1

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

  • @amanjotsingh5876
    @amanjotsingh5876 2 года назад +5

    Good explanation .... just one thing bro control your hands movement 😂😂 ... jokes apart..... keep up the good work

  • @ashuraj1981
    @ashuraj1981 2 года назад +4

    Do u read every comments striver, just asking.By the way thanks a lot for #FreekaTreeSeries❤

  • @SriHarshaChilakapati
    @SriHarshaChilakapati 2 года назад +13

    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 года назад +1

      He had cover this edge test case on Previous LCA video

  • @subirkumar6786
    @subirkumar6786 Год назад +3

    What if node p is present and node q is not present in the BST

  • @priyankaranawat8373
    @priyankaranawat8373 Месяц назад +1

    Thank you sooooo much

  • @deepakojha3216
    @deepakojha3216 2 года назад +5

    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  2 года назад +16

      I promised if you give me 10k likes, you did not 🥲
      Anyways will be up from Dec 1

    • @PrinceKumar-el7ob
      @PrinceKumar-el7ob 2 года назад +4

      @@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 года назад +1

      @@takeUforward apne mera resume roast kardia pr purra nhi dekha :c

  • @shwetanksingh5208
    @shwetanksingh5208 2 года назад +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 Год назад +1

    what in the case of skewed tree like 1->right = 2, 2->right = 3;

  • @thebibeksaha
    @thebibeksaha 2 года назад +1

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

  • @ishangujarathi10
    @ishangujarathi10 Год назад +1

    loved the intuition, amazing explanation as alwaysss!!!! tysm!!!

  • @himanshuranjan8657
    @himanshuranjan8657 2 года назад +1

    Line 13 should be : if(root == NULL) return root ;

    • @igaming_
      @igaming_ Год назад

      U can write return null or return root (both are correct)

  • @parthsalat
    @parthsalat 2 года назад +1

    Here are my detailed notes on this question:
    garmadon.notion.site/Lowest-Common-Ancestor-of-a-Binary-Search-Tree-f568d9e1505f4234bdbd045516e0d4e5

  • @debugagrawal
    @debugagrawal 2 года назад +2

    DSA God 😍🙌🚩🚀

  • @arpanseal5722
    @arpanseal5722 Год назад +1

    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  Год назад +3

      You can ignore if it works without them, I usually write it for cleaner code

    • @arpanseal5722
      @arpanseal5722 Год назад

      @@takeUforward Thank you sir. Got it. ❤️

  • @prafuljohn15
    @prafuljohn15 2 года назад +1

    Striver bhai c++ pr chal nahi raha hai aapka code

  • @shubhamkumarsingh8818
    @shubhamkumarsingh8818 3 месяца назад +1

    man, u r genius.
    what a brilliant way of teaching.

  • @prajapati-suraj
    @prajapati-suraj Месяц назад

    I struggled for 2 hours because I was considering bst as bt.... thank you so much for this...

  • @swayam50
    @swayam50 2 года назад +2

    Amazing video as always, you're tree series is helping a lot 🙂🙂

  • @ishwaripednekar5164
    @ishwaripednekar5164 2 года назад +2

    Keep it up, we need teachers like you!!

  • @babai2196
    @babai2196 2 года назад +1

    can this approach be applied to lca of binary tree

  • @arpanbanejee5143
    @arpanbanejee5143 2 года назад +2

    Thanks for this awesome series! you are the best!

  • @shivalikagupta3433
    @shivalikagupta3433 2 года назад +1

    Thank you so mcuh for all your hard work !!!

  • @piyushacharya7696
    @piyushacharya7696 Год назад

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

  • @iamnottech8918
    @iamnottech8918 2 месяца назад

    Wow!

  • @_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 ;
    }
    };

  • @adityapandey23
    @adityapandey23 7 дней назад

    Understood

  • @saranguru6100
    @saranguru6100 2 года назад +1

    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 ?

  • @Shivi32590
    @Shivi32590 Месяц назад

    understood

  • @prachigupta2430
    @prachigupta2430 Год назад

    Thanks for this much amazing content and explanation.
    Again very grateful 😊

  • @hitheshpk6030
    @hitheshpk6030 Месяц назад

    Understood

  • @himanshidafouty347
    @himanshidafouty347 2 месяца назад

    Understood

  • @Shubham-yc6nz
    @Shubham-yc6nz Месяц назад

    Thanks

  • @avanishmaurya2034
    @avanishmaurya2034 8 месяцев назад +1

    Nice

  • @ishwaripednekar5164
    @ishwaripednekar5164 2 года назад +1

    This is just outstanding

  • @tanmayjain5576
    @tanmayjain5576 Год назад

    Understood

  • @tanishkumar6682
    @tanishkumar6682 Год назад

    understood

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

  • @Preethamdivakar
    @Preethamdivakar 2 месяца назад

    super explaination bro🙏

  • @RAJKUMAR-q4c2x
    @RAJKUMAR-q4c2x 8 месяцев назад

    what if p and q are not present in BST ??

  • @diegolikescode
    @diegolikescode 7 месяцев назад

    Man, really good stuff!! Thank you for this!

  • @tech_wizard9315
    @tech_wizard9315 2 года назад

    I am a DSA beginner,is your trees series enough to crack tech giant's like Microsoft linkedin level companies?

  • @ashishchandra4078
    @ashishchandra4078 Год назад

    crystal clear explanation. Thank you Striver.

  • @editorera239
    @editorera239 2 года назад

    bhai kaafi pro level intuition h
    Thanks!

  • @605_samikrdas4
    @605_samikrdas4 Год назад

    soooo goood trulyyy

  • @culeforever5408
    @culeforever5408 7 месяцев назад +1

    Great Series 😀

  • @akashnandi1267
    @akashnandi1267 Год назад

    1 is missing bro pls correct it

  • @bhaveshrathod9898
    @bhaveshrathod9898 2 года назад

    Thanks for the video:)

  • @rishabhgupta9846
    @rishabhgupta9846 Год назад

    able to solve by myself

  • @ishaanchandak1258
    @ishaanchandak1258 10 месяцев назад

    link of the question ?

  • @theonlyisteve7261
    @theonlyisteve7261 2 года назад

    shit got real, nice1

  • @tech_wizard9315
    @tech_wizard9315 2 года назад +2

    I am a DSA beginner,is your trees series enough to crack tech giant's like Microsoft linkedin level companies?

  • @anonymous090
    @anonymous090 Год назад

    Thank you Bhaiya

  • @rishabhprasad8333
    @rishabhprasad8333 2 года назад

    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 года назад +5

      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? : (

  • @UECAshutoshKumar
    @UECAshutoshKumar Год назад

    Thank you sir

  • @GauravGangwar-r2v
    @GauravGangwar-r2v 3 месяца назад

    bro is genius .

  • @aaranyaksantra9933
    @aaranyaksantra9933 2 месяца назад

    nice solution

  • @sayakbasak587
    @sayakbasak587 Год назад

    thanks bhaiya

  • @Kpriyasing
    @Kpriyasing 2 года назад

    Thanks for such a nice explanation!

  • @tejalsaraswat
    @tejalsaraswat Год назад

    u r the besttt

  • @shikharai-tl4vb
    @shikharai-tl4vb 3 месяца назад

    good job :)

  • @harshitjaiswal9439
    @harshitjaiswal9439 7 месяцев назад

    understood

  • @abhinanda7049
    @abhinanda7049 4 месяца назад

    understood

  • @adityaramakrishnan969
    @adityaramakrishnan969 2 года назад

    Awesome code,video keep it uo

  • @hakunamatata-nl4js
    @hakunamatata-nl4js 3 месяца назад

    thank you

  • @Learnprogramming-q7f
    @Learnprogramming-q7f 6 месяцев назад

    thank you Bhaiya

  • @krishnarajs929
    @krishnarajs929 2 года назад

    if the given p and q nodes is not there .what we need to do?

  • @SiddheshKukade
    @SiddheshKukade Год назад

    thanks

  • @venutalla5932
    @venutalla5932 Год назад

    Tq sir

  • @abhishek__anand__
    @abhishek__anand__ Год назад

    Super

  • @dreamyme543
    @dreamyme543 2 года назад

    Understood:)

  • @roopeshn3301
    @roopeshn3301 2 года назад

    Understood

  • @iamnoob7593
    @iamnoob7593 7 месяцев назад

    US

  • @codebits2120
    @codebits2120 2 года назад

    Very clear explanation

  • @alesblaze4745
    @alesblaze4745 2 года назад

    thanks mate!

  • @NikhilGupta-zo5jh
    @NikhilGupta-zo5jh 2 года назад

    UnderStood

  • @deeyasings
    @deeyasings 2 года назад

    understood

  • @suvanshmahajan5902
    @suvanshmahajan5902 2 года назад

    "us"

  • @GhostVaibhav
    @GhostVaibhav 7 месяцев назад

    Understood🔥

  • @ajayypalsingh
    @ajayypalsingh 2 года назад

    💚

  • @BharatVaad
    @BharatVaad 2 года назад

    great

  • @zeyadalbadawy2245
    @zeyadalbadawy2245 Год назад

    Amazing sir

  • @ashutoshtripathi8257
    @ashutoshtripathi8257 2 года назад

    🔥🔥❤️

  • @DevanshuAugusty
    @DevanshuAugusty Год назад

    tc = logn right?

  • @player-te8tf
    @player-te8tf 2 года назад +1

    striver runs java code in c++ mode (7:52) on leetcode, halke me mt lena god hai bro apna

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