【问题标题】:access struct with a function, how to save the value?用函数访问结构,如何保存值?
【发布时间】:2017-10-12 15:25:07
【问题描述】:

有谁知道如何将值保存到左侧或右侧的二叉树中? 例如我们有 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
}

有人知道吗??

提前致谢

【问题讨论】:

  • 除非你是在站在火车上的智能手机上使用 vi,否则你的编码风格绝对应受谴责。
  • 请联系您的老师。您在一些核心概念方面存在根本问题,需要在教学环境中解决,而不是在问答网站中解决。

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


【解决方案1】:

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

你可以写:

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

【讨论】:

  • 我如何访问左侧?当我尝试这个时出现警告:tree->root->left = value 我该如何解决这个问题?
  • root-&gt;leftroot-&gt;right 都必须指向 A 类型的对象;当您在新节点中排序时,这些对象通常存在。但是——请不要消极——这个例子可能有点超出你的成熟度吗?开始学习 C 时,二叉搜索树不是合适的东西......
【解决方案2】:

我认为讨论你的代码没有意义。:) 甚至结构定义也没有分号。

考虑到这些结构定义

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 ) ) { /*...*/ }

【讨论】:

    猜你喜欢
    • 2020-09-08
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 2022-01-17
    • 2021-06-10
    相关资源
    最近更新 更多