我刚刚开始学习 C 并尝试用 struct 制作二叉树。 当我尝试在 main() 中使用 addTreeNode 时,出现以下编译错误: “addTreeNode 的类型冲突” 和“将‘BinaryTree’(又名‘struct BinaryTree’)传递给不兼容类型‘BinaryTree *’(又名‘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二叉树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23974953/