用函数访问struct,如何保存值?

时间:2017-10-12 15:25:08

标签: c insert binary-tree binary-search-tree

有谁知道如何将值保存到左侧或右侧的二叉树中? 例如,我们有2个结构:

struct A
{
    int a;
    struct A *left;
    struct A *right;
}

struct B
{
    A *root;
}

我们有一个功能:

void insert(B *tree, int value)
{
    if(tree== NULL)
    {
        tree= (B*) malloc (sizeof(B));
    }
    else if(tree!=NULL)
    {
        tree->root->a = value;
        tree->root->left = NULL;
        tree->root->right = NULL;
    }

现在我们有根...... 但是如何在左右两侧初始化价值?

else if(tree->apointer->a< value)
{
    tree->root->left = value // with & wont work cause is a pointer to integer
}

有谁知道??

提前致谢

2 个答案:

答案 0 :(得分:0)

使用tree= (B*) malloc (sizeof(B));,您可以创建B类型的对象,但不要创建A可指向的tree->root类型的对象。访问tree->root->aroot的其他成员则是未定义的行为;

你可以写:

tree = malloc (sizeof(B));
tree->root = malloc(sizeof(A));

答案 1 :(得分:0)

我认为讨论你的代码是没有意义的。:)甚至结构定义都是用分号编写的。

考虑到这些结构定义

struct A
{
    int value;
    struct A *left;
    struct A *right;
};

struct B
{
    struct A *root;
};

并假设在main中有以下树的声明

int main( void )
{
    struct B tree = { NULL };
    //...

然后可以通过以下方式定义函数insert

int insert( struct B *tree, int value )
{
    struct A **node = &tree->root;

    while (*node)
    {
        if (value < (*node)->value)
        {
            node = &(*node)->left;
        }
        else
        {
            node = &(*node)->right;
        }
    }

    *node = malloc(sizeof(struct A));
    int success = *node != NULL;

    if ( success )
    {
        (*node)->value = value;
        (*node)->left = NULL;
        (*node)->right = NULL;
    }

    return success;
}

该功能可以像

一样调用
insert( &tree, value );

或其调用可以包含在if语句

if ( insert( &tree, value ) ) { /*...*/ }