简体   繁体   中英

C binary tree struct

I've just started to learn C and trying to make a binary tree with struct. When I try to use addTreeNode in main() I get the following compile errors: "Conflicting types for addTreeNode" and "Passing 'BinaryTree' (aka 'struct BinaryTree') to parameter of incompatible type 'BinaryTree *' (aka 'struct *BinaryTree')"

Am I doing something fundamentally wrong here?

#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;
}

change this line

tree = addTreeNode(2, tree);

to

tree = addTreeNode(2, &tree);

Your function requires passing by pointer, yet you pass by value.

EDIT:

Since you are allocating your struct in function BinaryTree *addTreeNode you should change BinaryTree tree; to BinaryTree *tree; inside main . Also your function returns pointer to BinaryTree* which cannot be assign to a variable of type BinaryTree

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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