2017-10-12 194 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)) { /*...*/ } 
相關問題