【问题标题】:Error in finding lowest common ancestor in tree在树中查找最低共同祖先时出错
【发布时间】:2017-07-08 17:59:06
【问题描述】:

我正在尝试在树中找到两个给定值的最低共同祖先。

我的方法是遍历树的左下角并检查各个节点是否有两个节点在它们下面。第一个给出匹配的节点是最低的共同祖先。

谁能告诉我这个函数的错误。

/*
Node is defined as 

typedef struct node
{
   int data;
   node * left;
   node * right;
}node;

*/


bool find(node *root,int val)  //to check if the value exist under the given node or not
{
    if(root==NULL)
        return false;
    if(root->data==val)
        return true;

    if((root->left&&find(root->left,val))||(root->right&&find(root->right,val)))
        return true;
    return false;
}


node * lca(node * root, int v1,int v2)   //to find the lowest common ancestor
{
    if(root==NULL)
        return NULL;
    static node* ans=NULL;
    lca(root->left,v1,v2);  //traversing to the bottom of the tree
    lca(root->right,v1,v2);

    if((find(root->left,v1)&&find(root->right,v2))||(find(root->left,v2)&&find(root->right,v1)))   //checking the existence of both nodes under the tree
    {
        if(ans==NULL)
            ans=root;
    }

    return ans;  //returning the lca
}

【问题讨论】:

  • 运行代码时会发生什么?与预期结果有何不同?

标签: c++ data-structures tree


【解决方案1】:

如果找到结果,您的递归函数应该只返回一个节点。如果未找到结果节点,它应该返回NULL。如果找到节点则中断,否则继续。我会这样做:

node * lca(node * root, int v1,int v2)   //to find the lowest common ancestor 
{
    if(root==NULL)
        return NULL;

    node* ans=NULL;

    // search the left child tree
    ans = lca(root->left,v1,v2); 
    if (ans != NULL)
      return ans; // if you found it you are finished

    // search the right child tree
    ans = lca(root->right,v1,v2);
    if (ans != NULL)
      return ans; // if you found it you are finished

    // test this tree node
    if( (find(root->left,v1)&&find(root->right,v2)) ||
        (find(root->left,v2)&&find(root->right,v1)))
    {
        // If the condition is true, this node is the result
        return root;
    }

    return NULL; // Neither this node nor any subordinate node of this node is the result 
}

【讨论】:

    猜你喜欢
    • 2011-07-28
    • 1970-01-01
    • 2012-11-08
    • 2017-07-28
    • 2014-05-24
    • 2012-01-16
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    相关资源
    最近更新 更多