L47. LCA in Binary Search Tree

Поділитися
Вставка
  • Опубліковано 23 січ 2025

КОМЕНТАРІ • 130

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

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

  • @divyansh2212
    @divyansh2212 2 роки тому +55

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

  • @galleryofjatin19
    @galleryofjatin19 2 роки тому +69

    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!

  • @SriHarshaChilakapati
    @SriHarshaChilakapati 3 роки тому +15

    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

    • @mayurbhor2231
      @mayurbhor2231 20 днів тому

      Perfect

  • @shubhamkumarsingh8818
    @shubhamkumarsingh8818 7 місяців тому +1

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

  • @karthik-varma-1579
    @karthik-varma-1579 3 місяці тому +1

    Thanks Stirver for Tree ka playlist i was able to solve this problem by myself. Thanks a lot.

  • @prajapati-suraj
    @prajapati-suraj 5 місяців тому

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

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

    Great Series 😀

  • @diegolikescode
    @diegolikescode 11 місяців тому

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

  • @aaluSandwich
    @aaluSandwich 3 роки тому +38

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

      This guy has haters?
      He is an inspiration bro🙂

  • @rahulpalivela1449
    @rahulpalivela1449 29 днів тому

    great explanation but one catch is we're missing/skipping the edge case , whether the nodes actually exist after the splitting node , cause the function might return the LCA even if one of the two p or q is actually missing in the tree , for that we have to right a check function before running the lca function
    bool exists(Node* root, int val) {
    while (root != NULL) {
    if (root->data == val) return true; // Node found
    else if (val < root->data) root = root->left; // Search in left subtree
    else root = root->right; // Search in right subtree
    }
    return false; // Node not found
    }
    // Function to find the LCA
    Node* lca(Node* root, int p, int q) {
    while (root != NULL) {
    if (root->data > p && root->data > q) {
    root = root->left;
    } else if (root->data < p && root->data < q) {
    root = root->right;
    } else {
    return root; // Found the LCA
    }
    }
    return NULL; // If the LCA is not found
    }
    int main() {
    Node* root = new Node(20);
    root->left = new Node(10);
    root->right = new Node(30);
    root->left->left = new Node(5);
    root->left->right = new Node(15);
    root->right->right = new Node(40);
    int p = 5;
    int q = 2; // Testing edge case where one node (2) does not exist in the tree
    // Verify existence of both nodes
    if (exists(root, p) && exists(root, q)) {
    Node* result = lca(root, p, q);
    if (result == NULL) {
    cout

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

    Great approach

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

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

  • @vivekjaiswar6825
    @vivekjaiswar6825 3 роки тому +16

    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?

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

    Keep it up, we need teachers like you!!

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

    Thank you sooooo much

  • @Preethamdivakar
    @Preethamdivakar 6 місяців тому

    super explaination bro🙏

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

    Nice

  • @aaranyaksantra9933
    @aaranyaksantra9933 6 місяців тому

    nice solution

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

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

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

    Thank you So much !

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

    Thanks for this awesome series! you are the best!

  • @GauravGangwar-r2v
    @GauravGangwar-r2v 7 місяців тому

    bro is genius .

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

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

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

    Amazing sir

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

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

  • @GhostVaibhav
    @GhostVaibhav 11 місяців тому

    Understood🔥

  • @priyankasetiya1358
    @priyankasetiya1358 7 місяців тому +2

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

  • @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. ❤️

  • @shikharai-tl4vb
    @shikharai-tl4vb 7 місяців тому

    good job :)

  • @RAJKUMAR-q4c2x
    @RAJKUMAR-q4c2x Рік тому

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

  • @iamnottech8918
    @iamnottech8918 6 місяців тому

    Wow!

  • @saranguru6100
    @saranguru6100 3 роки тому +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 ?

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

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

  • @Learnprogramming-q7f
    @Learnprogramming-q7f 10 місяців тому

    thank you Bhaiya

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

    crystal clear explanation. Thank you Striver.

  • @himanshidafouty347
    @himanshidafouty347 6 місяців тому

    Understood

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

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

  • @Shubham-yc6nz
    @Shubham-yc6nz 5 місяців тому

    Thanks

  • @hakunamatata-nl4js
    @hakunamatata-nl4js 7 місяців тому

    thank you

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

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

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

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

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

    link of the question ?

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

    can this approach be applied to lca of binary tree

  • @deepakojha3216
    @deepakojha3216 3 роки тому +6

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

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

    • @PrinceKumar-el7ob
      @PrinceKumar-el7ob 3 роки тому +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 3 роки тому +1

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

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

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

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

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

    Thanks for such a nice explanation!

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

    Very clear explanation

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

    bhai kaafi pro level intuition h
    Thanks!

  • @harshitjaiswal9439
    @harshitjaiswal9439 11 місяців тому

    understood

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

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

  • @songlover2538
    @songlover2538 14 днів тому

    submit bhi n hua y toh

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

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

    1 is missing bro pls correct it

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

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

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

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

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

    DSA God 😍🙌🚩🚀

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

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

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

    This is just outstanding

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

    nice explanation....

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

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

    tc = logn right?

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

    thanks bhaiya

  • @iamnoob7593
    @iamnoob7593 10 місяців тому

    US

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

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

    thanks

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

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

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

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

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

    Thanks for the video:)

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

    thanks mate!

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

    Thank you sir

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

    understood

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

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

    Thank you Bhaiya

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

    Tq sir

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

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

    Awesome code,video keep it uo

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

    Is this correct?
    TC-> O(H)
    SC-> O(1) // Iterative soltion
    class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    while(true){
    if(root==null) return null;
    if((root.val>p.val && root.val p.val && root.val>p.val) root=root.left;
    else root=root.right;
    }
    }
    }

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

    Understood

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

    💚

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

    u r the besttt

  • @605_samikrdas4
    @605_samikrdas4 Рік тому

    soooo goood trulyyy

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

    🔥🔥❤️

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

    great

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

    Super

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

    able to solve by myself

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

    Understood:)

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

    shit got real, nice1

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

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

  • @NikhilGupta-zo5jh
    @NikhilGupta-zo5jh 2 роки тому

    UnderStood

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

    "us"

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

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

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

    Understood

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

    understood

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

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

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

    understood

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

    Understood

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

    Understood

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

    understood

  • @sid1993ful
    @sid1993ful 27 днів тому

    Understood