【问题标题】:tutorials about Tree Data structures with left,right and parent nodes关于具有左、右和父节点的树数据结构的教程
【发布时间】:2012-03-05 22:56:33
【问题描述】:

有人可以指导我使用 C 在结构中具有左、右和父节点的一些关于树数据结构的教程。我用 Google 和 Stack Overflow 搜索过,但我只找到只有 Node *left 和 Node *right 的树。 为了清楚起见,我正在搜索树教程:

struct Node {
  int data;
  Node *parent, *left, *right;  
};  

【问题讨论】:

  • 您具体想了解什么?这是什么树(一般二叉树?红/黑?)
  • 那些没有左节点的节点呢?还是父母?
  • 这是关于二叉树的。目的是测试父级的值是什么,所以我需要在节点的结构中添加 *parent 。我已经完成了,我遇到了分段错误,我觉得我没有真正理解,我需要教程。

标签: c algorithm binary-tree nodes


【解决方案1】:

我不确定我是否跟随。实际上,我认为您找不到任何教程,因为这更像是与算法相关的问题。据我记得 CLR1 稍微介绍了这个话题。

这是一个示例,说明添加对于此类树的外观。但我认为 CLR 涵盖的内容比我用几行代码举例说明的要好。

int add(node **root, int value)
{
   node *var,*parent_node;
   var = malloc(sizeof(node));
   var->data = value;
   /* if the tree hasn't been initialised we do so now */
   if (*root == NULL)
   {
      var->parent = NULL;
      var->left = NULL;
      var->right = NULL;
      return 0;
   }
   /* we look for the future parent of our new node */
   parent_node = search(*root,value);
   /* if the value already exists we return -1 */
   if (parent_node->data == value)
       return 0;
   var->parent = parent_node;
   /* put the new node into position */
   if (parent_node->data > value)
       parent_node->left = var;
   else
       parent_node->right = var;
   return 0;
}

该搜索功能可以是任何教科书式的二叉树搜索功能,因为在您进行搜索时父级不会出现。虽然应该提到,如果找不到该值,平均搜索将返回 NULL,因此您可能需要修改它以返回 NULL 的“父级”。比如:

node *search(node *root, int value)
{
   node *var, *cursor;
   cursor = root;
   while(cursor->data != value)
   {
      if (cursor->data > value)
          var = cursor->left;
      else
          var = cursor->right;
      if (var == NULL)
          return cursor;
      cursor = var;
   }
   return cursor;
}  

【讨论】:

    【解决方案2】:

    我认为这个tree structure 可以满足您的所有需求。先看看tree.hh,不过是c++的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多