我刚刚开始学习C并尝试使用struct制作二叉树。
当我尝试在main()中使用addTreeNode时,出现以下编译错误:
“ addTreeNode的类型冲突”
和“将'BinaryTree'(aka'struct BinaryTree')传递给不兼容类型'BinaryTree *'(aka'struct * BinaryTree')的参数”

我在这里做错什么吗?

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

struct BinaryTree
{
    int data;
    struct BinaryTree *left;
    struct BinaryTree *right;
};

typedef struct BinaryTree BinaryTree;

BinaryTree *addNode(int element, BinaryTree *tree);

int main(int argc, const char * argv[])
{

    BinaryTree *tree;
    tree = addTreeNode(2, tree);

 return 0;
}

// add the given element element to the tree
BinaryTree *addTreeNode(int element, BinaryTree *tree)
{
    if (tree == NULL)
    {
        tree = malloc(sizeof(BinaryTree));
        tree->data = element;
    }
    else if (element < tree->data)
    {
        addTreeNode(element, tree->left);
    }
    else
    {
      addTreeNode(element, tree->right);
    }
    return tree;
}

最佳答案

改变这条线

tree = addTreeNode(2, tree);




tree = addTreeNode(2, &tree);


您的函数需要按指针传递,但按值传递。

编辑:

由于要在函数BinaryTree *addTreeNode中分配结构,因此应在BinaryTree tree;内部将BinaryTree *tree;更改为main。此外,您的函数还会返回指向BinaryTree*的指针,该指针无法分配给BinaryTree类型的变量

关于c - C二叉树结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23974953/

10-12 14:47