将节点添加到树问题[关闭]

问题描述 投票:0回答:1

我在向搜索树添加节点时遇到问题。我有很多错误,比如“指针和整数之间的比较”和“期望的char但参数类型为char *”。这是我的代码:

 void addNode(WordTreeNode ** tree, char tok)
 {
   WordTreeNode *temp = NULL;
   if(!(*tree))
   {
      temp = (WordTreeNode *)malloc(sizeof(WordTreeNode));
      temp->leftChild = temp->rightChild = NULL;
      temp->name = tok;
      *tree = temp;
      return;
   }

   if(tok < (*tree)->name)
   {
      addNode(&(*tree)->leftChild, tok);
   }
   else if(tok > (*tree)->name)
   {
      addNode(&(*tree)->rightChild, tok);
   }

}
c pointers tree header structure
1个回答
1
投票

我认为你的成员namechar *类型。使用strcmp而不是<>char*而不是char。将您的代码更改为:

void addNode(WordTreeNode ** tree, char * tok)
                                     // ^
{
    WordTreeNode *temp = NULL;
    if(!(*tree))
    {
        temp = (WordTreeNode *)malloc(sizeof(WordTreeNode));
        temp->leftChild = temp->rightChild = NULL;

        temp->name = malloc( strlen(tok)+1 );
        strcpy( temp->name, tok );
        // don't forget to free the memory when youe destroy the node

        *tree = temp;
        return;
    }

    if( strcmp( tok, (*tree)->name) < 0 )
     // ^^^^^^
    {
        addNode(&(*tree)->leftChild, tok);
    }
    else if ( strcmp( tok, (*tree)->name) > 0 )
           // ^^^^^^
    {
        addNode(&(*tree)->rightChild, tok);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.