【问题标题】:Find ancestors of given node in a n-ary tree c++在n-ary树c ++中查找给定节点的祖先
【发布时间】:2019-06-25 02:35:14
【问题描述】:

给定一个大的 n 叉树,我需要创建一个递归函数来打印一个叶子的所有祖先,例如 n 叉树结构为

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

这是我使用的函数,但给出了错误的答案:

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

【问题讨论】:

  • 如果没有找到孩子,你不会返回任何东西......
  • Offtopic:为什么会有那么多指针? int* data:你有没有引用一些int e。 G。在一个完全不同的结构中?如果您只需要该值,请删除指针。 struct Node** children;: 指针数组???为什么普通数组还不够用?
  • 您确定要比较 int 指针吗?例如:即使ab 保持相同的值,int a = 7; Node root = { }; root.data = &amp;a; int b = 7; printAncestors(&amp;root, &amp;b); 也不会找到节点...
  • @Aconcagua 我用指向节点的数据来实现树
  • 使用指向数据的指针可能有意义也可能没有意义,这取决于用例......所以,我经常看到指针在不合适的时候被使用,不过(struct Node** child 至少看起来像一,没有更多信息......)。但是通过比较指针本身,如果您使用节点指向的特定int,您只能找到注释。你确定这是你想要的吗?即使 if 使用指向数据的指针,您也不想按值查找节点,i。 e. bool printAncestors(NaryNode* root, int data) { if(*root-&gt;data == data) }?

标签: c++ recursion tree


【解决方案1】:

您最后缺少返回值,即使root-&gt;nchild 为零,您也可以进入循环并访问root-&gt;child[i]
这两者都会导致未定义的行为。

我会用 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;
}

【讨论】:

  • 感谢您的帮助。其实我试过这个函数,但是当我最后添加一个返回值时它没有给出祖先的值所以它没有进入循环!我不明白为什么
  • @WehbeD 可能是由于指针使用而找不到您的值 - 请参阅我对问题的最新评论...
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多