Binary Search Tree : Lowest Common Ancestor

  • + 1 comment

    C++ solution :

    Node *lca(Node *root, int v1,int v2) {
    		// Write your code here.
            while((v1>root->data && v2>root->data) || (v1<root->data && v2<root->data))
            {
                if (v1>root->data) root=root->right;
                else root=root->left;
            }
            return root;
        }
    
    • + 1 comment
      Node *add1 [25];
           Node *add2[25];
              int i=0,j=0;
          Node *lca(Node *root, int v1,int v2) {
      		// Write your code here.
             
              if(v1>root->data) {
                  root=lca(root->right,v1,v2);
                  add1[i++]=root;
                  
              }
               else if(v2>root->data) {
                  root=lca(root->right,v1,v2);
                  add2[j++]=root;
                  
              }   
              else if(v1<root->data) {
                  root=lca(root->left,v1,v2);
                  add1[i++]=root;
                  
              }
               else if(v2<root->data) {
                  root=lca(root->left,v1,v2);
                  add2[j++]=root;
                  
              }   
              Node *a;
              for(int i=0;i<25;i++){
                  for(int j=0;j<25;j++){
                      if(add1[i]==add2[2]) {a= add1[i]; return a;}
                  }
              }
      
              
          }
      

      why this not working

      • + 0 comments
        1. i was basically storing the address of the of each node through which we are passing for v1 and v2 in add1 and add2 respectively
        2. i want to ask few questions:-
        3. solution is a structure (in this question) , when we are calling Lca function (MYTREE.LCA(ROOT,V1,V2) , does the "instance of struct solution " will have --> add1[25] , add2[25], int i,j ; when function is called
        4. on each function call (root=lca(root->left,v1,v2) ) in each "IF" statement does the add1[25] , add2[25], int i,j , will again take memory OR one single copy of add1[25] , add2[25], int i,j ; is only there, as only one insance is made;