【问题标题】:void implementation error for Insert function of binary search tree (In C)二叉搜索树插入函数的void实现错误(C语言)
【发布时间】:2020-08-26 04:23:09
【问题描述】:

对于一个作业,我被要求为二叉搜索树编写插入函数,其中项目指向一个结构,该结构包含一个单词以及它出现的次数。在为 BST 搜索插入函数的标准实现后,我想到了这个:

// Insert an item into the tree rooted at node n.
// If the tree already has a node for that item, do nothing.

void insert(BSTnode *n, void *item, int compare(void * a, void * b)){
  BSTnode *new_node = (BSTnode *)item;
  BSTnode *currentNode = n;
    if(n==NULL){
      BSTnode *new = createNode(item);
      return new;
    }

    else if(compare(((WordCount*)new_node->item)->word, ((WordCount*)currentNode->item)->word)==0){
      return;
    }

    else if(compare(((WordCount*)new_node->item)->word, ((WordCount*)currentNode->item)->word) > 0){
      n->right = insert(n->right, item, compare);
    }

    else{
      n->left = insert(n->left, item, compare);
    }
}

但是我得到了一个“没有被忽略的无效值”,因为我做不到

 n->right = insert(n->right, item, compare);

如何修改这个插入函数?我被卡住了,真的不知道该怎么做,因为它是一个 void 函数。

【问题讨论】:

  • @ovecssomuchjk 不要把时间花在修改错误的代码上。编写你自己的好代码。:)

标签: c data-structures binary-search-tree void-pointers


【解决方案1】:

试试这个

//start of insert
void insert(BSTnode *n, void *item, int compare(void * a, void * b))
{
    BSTnode *new_node = (BSTnode *)item;
    BSTnode *currentNode = n;
    if(n==NULL) // if root is null
    {
        BSTnode *node = createNode(item);
        n = node;
        return;
    }
    else
    {
        insertSub(n, item, compare); // walk over the tree recursive with itemsub
    }
}

void insertSub(BSTnode *n, void *item, int compare(void * a, void * b))
{
    BSTnode *new_node = (BSTnode *)item;
    BSTnode *currentNode = n;
    if(compare(((WordCount*)new_node->item)->word, ((WordCount*)currentNode->item)->word) > 0)
    {
        if(n->right == NULL) //if right child = null then create the desired node
        {
            n->right = createNode(item);
            return; // go out of the tree
        }
        else
        {
            insertSub(n->right, item, compare); walk
        }
    }
    else
    {
        if(n->left == NULL) //if left child = null then create desired node
        {
            n->left = createNode(item);
            return; // go out of the tree
        }
        else
        {
            insertSub(n->left, item, compare);
        }
    }
}

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    相关资源
    最近更新 更多