【问题标题】:Inserting node into BST (C)将节点插入 BST (C)
【发布时间】:2020-07-01 23:12:41
【问题描述】:

我正在尝试将一个节点插入到 bst 中,到目前为止我有以下内容

typedef struct _StoreNode *Connect;

typedef struct  _StoreNode {
   NumberFrequency  data;
   Connect   left;
   Connect   right;
} StoreNode;

Struct _StoreRep{
   Connect tree;
};

static Connect newConnect(char *w) {
   Connect n = malloc(sizeof(*n));
   n->data.frequency = 1;
   n->data.number = (char *)malloc(strlen(w) * sizeof(char));
   strcpy(n->data.number, w);
   n->left = NULL;
   n->right = NULL;
   return n;
}

NumberFrequency * insert(Connect n, char *w)
{
    if (n == NULL)
      return &newConnect(w)->data;
    else if (strcmp(n->data.number,w) > 0)
      return insert(n->left, w);
    else if (strcmp(n->data.number,w) < 0)
      return insert(n->right, w);
    else
       n->data.frequency = n->data.frequency+1;
    
   return &n->data;
}

NumberFrequency *DictInsert(Dict d, char *w){
   return insert(d->tree, w);
}

我正在尝试返回指向要添加到 BST 中的项目的指针。没有抛出错误,但没有任何反应。非常感谢您的帮助!

【问题讨论】:

  • 您没有将新节点与前一个节点连接起来。您只是在创建一个节点,但没有将其连接到根节点。

标签: c binary-search-tree


【解决方案1】:

您需要实际更改内部(非叶)节点的连接。这是更新后的函数(我没有测试过它的语法错误,但你应该明白要点):

NumberFrequency * insert(Connect n, char *w)
{
    if (n == NULL)
      return &newConnect(w)->data;
    else if (strcmp(n->data.number,w) > 0)
      n->left = insert(n->left, w);
    else if (strcmp(n->data.number,w) < 0)
      n->right = insert(n->right, w);
    else
       n->data.frequency = n->data.frequency+1;
    
   return &n->data;
}

【讨论】:

  • 这不会按原样工作 - 递归调用不会返回新节点作为其结果。
  • 我在行 n->left = insert(n->left, w); 上收到关于指针类型不兼容的错误;和 n->right = insert(n->right, w);
【解决方案2】:

试试这个插入函数

if (n == NULL)
      return &newConnect(w)->data;

else {
        Connect *temp_ = n, *temp = NULL;
        while (temp_ != NULL) {
            if (strcmp(temp_->data.number, w) > 0) {
                temp = temp_;
                temp_ = temp_->r;
            }

            else if (strcmp(temp_->data.number, w) < 0) {
                temp = temp_;
                temp_ = temp_->l;           
            }
        }

        if (strcmp(temp->data.number, w) > 0) {
              temp->r = newConnect(w);
              return &temp->r->data;
        }

        else if (strcmp(temp_->data.number, w) < 0) {
              temp->l = newConnect(w);
              return &temp->r->data;          
        }
    }

n->data.frequency = n->data.frequency+1;

return &n->data;

【讨论】:

    猜你喜欢
    • 2017-06-14
    • 1970-01-01
    • 2019-09-06
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    相关资源
    最近更新 更多