C二叉树结构

标签 c struct binary-tree

我刚刚开始学习 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/

相关文章:

java - 可下载应用程序中的不同语言

宏可以执行复合赋值吗

c++ - 如何调整结构 vector 的大小?

c++ - 从文件构造树

c - 编写我自己的系统调用来计算字符串指针中出现了多少个o

c - 错误 "Invalid initializer"

c - 当在 powerPC sizeof 上增加指向结构数组的指针时,无法按预期工作

python - 如何在 Python 中为我的二叉树实现 OS-Rank() 函数?

c++ - 二叉搜索树- breadthFirst函数调用

您可以在 C 中为现有的用户定义类型键入别名吗?