2017-10-12 176 views
-1

没有人知道如何将值保存到左侧或右侧的二叉树中? 比如我们有2层结构:用函数访问struct,如何保存值?

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

现在我们有根... 但如何initiliase在右侧和左侧的价值?

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

有谁知道?

在此先感谢

+1

除非您使用在智能手机在火车上站起来VI,您的编码风格是绝对应该受到谴责。 – Bathsheba

+0

请联系你的老师。您在教学情境中需要解决某些核心概念而非问答网站时存在根本性问题。 – Arkadiy

回答

0

随着tree= (B*) malloc (sizeof(B));,创建B类型的对象,但你没有创建A类型的对象,该tree->root可以指向。访问tree->root->aroot的其他成员则是未定义行为;

你可以写:

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

以及如何访问左侧?有一个警告,当我尝试这个: 树 - >根 - >左=值 我该如何解决这个问题? – Newuser1234567

+0

'root-> left'和'root-> right'都必须指向'A'类型的对象;这些对象通常在您排序新节点时存在。但是 - 请不要拿它否定 - 这个例子是否会超出你的成熟度水平?二进制搜索树在开始学习C时不适合 –

0

我觉得这是没有意义的讨论你的代码:)即使结构定义,不写分号。

考虑到这些结构定义

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

struct B 
{ 
    struct A *root; 
}; 

并且假设在main有那么函数insert可以定义如下方式

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

的下面的声明

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

付福nction可以这样调用

insert(&tree, value); 

或手机的通话可以被封闭在一个if语句

if (insert(&tree, value)) { /*...*/ } 
相关问题