c++least-common-ancestor

LCA descendant nodes


I'm trying to get the least common ancestor of two nodes in a tree. I have tried out, but the problem is if one node is the descendant node for other I was unable to get the LCA.
I tried solving it, then it was working only for descendant nodes. Didn't know how to proceed with this.

Node* Tree::LCA(Node* root, Node* n1, Node* n2) {
    list<Node*> a1,a2;

    while(n1 != NULL) {
        a1.push_back(n1->parent);
        n1 = n1->parent;
    }

    while(n2 != NULL) {
        a2.push_back(n2->parent);
        n2 = n2->parent;
    }

    while(!a1.empty() && !a2.empty() && a1.back() == a2.back()) {   
        a1.pop_back();
        a2.pop_back();
    }

    if( a1.back() != a2.back()) {
        Node* rn = a1.back();
        cout << " LCA of r-U and r_v is " << rn->index << endl;
    }
}

Solution

  • Node* Tree::LCA(Node* root, Node* n1, Node* n2) {
        list<Node*> a1,a2;
    
        while(n1 != NULL) {
            a1.push_back(n1); // push n1 
            n1 = n1->parent;
        }
    
        while(n2 != NULL) {
            a2.push_back(n2);  // push n2
            n2 = n2->parent;
        }
    
        Node* old; // create new node
        while(!a1.empty() && !a2.empty() && a1.back() == a2.back()) {
            old = a1.back(); // store the node before popping
            a1.pop_back();
            a2.pop_back();
        }
    
        if( a1.back() != a2.back()) {
           // Node* rn = a1.back();  //not needed
            cout << " LCA of r-U and r_v is " << old->index << endl; // changed 
        }
    }
    

    This might be helpful.