简体   繁体   English

在n元树c中查找给定节点的祖先

[英]Find ancestors of given node in a n-ary tree c++

Given a larg n-ary tree, I need to create a recursive function that prints all the ancestors of a leaf for example where the n-ary tree structure is given as 给定一棵大n元树,我需要创建一个递归函数来打印叶子的所有祖先,例如,其中n元树结构为

 typedef struct sNaryNode
 {
    int *data;
    int nchild;
    struct sNaryNode **child;
 } NaryNode;

Here is the function I used but that gives a wrong answer: 这是我使用的函数,但给出了错误的答案:

bool printAncestors(NaryNode *root, int *data) 
{ 
  int i=0;

   if (root == NULL) 
   return false; 

   if (root->data == data) 
   return true; 

   do
   {
      auto b=printAncestors(root->child[i], data);
      if(b)
      {   
          cout<<*root->data<<" ";
          return true;
      }
      else
          i++;
   }
   while(i<root->nchild);
}

You're missing a return value at the end, and you may enter the loop and access root->child[i] even if root->nchild is zero. 您最后缺少一个返回值,即使root->nchild为零,也可能进入循环并访问root->child[i]
Both of those will cause undefined behaviour. 两者都会导致不确定的行为。

I would write this with a for-loop instead: 我会用for循环来代替:

bool printAncestors(const NaryNode *root, const int *data) 
{ 
    if (root == nullptr) 
        return false; 

    if (root->data == data) 
        return true;

    for (int i = 0; i < root->nchild; i++)
    {
        if (printAncestors(root->child[i], data))
        {   
            cout << *root->data << " ";
            return true;
        }
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM