繁体   English   中英

二叉搜索树的插入 function 的无效实现错误(在 C 中)

[英]void implementation error for Insert function of binary search tree (In C)

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

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

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

尝试这个

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

我希望这可以帮助你:)

暂无
暂无

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

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