2013-03-13 66 views
0

我正在嘗試獲取樹中兩個節點的最不共同的祖先。我試過了,但問題是if one node is the descendant node for other我無法獲得LCA。
我試着解決它,然後它只爲後代節點工作。不知道如何繼續這個。LCA後代節點

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

回答

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

這可能會有幫助。

1

你開始從n1->parentn2->parent推動。推動n1n2以推動他們的父母和其他祖先。所以,你的代碼應該是:

Node* Tree::LCA(Node* root, Node* n1, Node* n2) { 
    list<Node*> a1,a2; 
    a1.push_back(n1); // line to be added 

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

    a2.push_back(n2); // line to be added 
    while(n2 != NULL) { 
     a2.push_back(n2->parent); 
     n2 = n2->parent; 
    } 
    // rest of code 
+0

呀。我仍然有同樣的問題。 – user322 2013-03-13 10:52:22