【问题标题】:LCA descendant nodesLCA 后代节点
【发布时间】:2013-03-13 10:43:35
【问题描述】:

我正在尝试获取树中两个节点的最小共同祖先。我已经尝试过了,但问题是if one node is the descendant node for other 我无法获得 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;
    }
}

【问题讨论】:

    标签: c++ least-common-ancestor


    【解决方案1】:

    您从n1-&gt;parentn2-&gt;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
    

    【讨论】:

    • 是的。我还是有同样的问题。
    【解决方案2】:
    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 
        }
    }
    

    这可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-18
      • 1970-01-01
      相关资源
      最近更新 更多