2016-11-29 4 views
0

プログラミングcでバイナリツリーを実装しようとしていました。それは価値だけを取っていますが、期待どおりの結果を表示していません。バイナリツリーを実装するのに必要な助け。ここでは私が長年試しているコードを追加しました。プログラミングのバイナリツリーインプリメンテーションコードの問題

#include<stdio.h> 
#include<stdlib.h> 
struct node 
{ 
    int data; 
    struct node*left; 
    struct node*right; 
}; 
int i,parent; 
struct node*root=NULL; 
struct node*newnode,*temp[]; 
void display(struct node*); 

void display(struct node *root) 
{ 
    if(root != NULL){ 
     printf("%d\t",root->data); 
     display(root->left); 
     display(root->right); 
    } 
} 
void add(int num) 
{ 
    for(i=0;i<num;i++) 
    { 
     newnode=(struct node*)malloc(sizeof(struct node)); 
     newnode->left=newnode->right=NULL; 
     newnode->data=i+1; 

     if(i==0)root=newnode;continue; 
     parent=(i-1)/2; 

     if(i%2==0)temp[parent]->right=newnode; 

     else temp[parent]->left=newnode; 

    } 
} 
int main() 
{ 
    int num; 
    printf("enter a binary number:"); 
    scanf("%d",&num); 
    display(root); 

} 
+1

'add 'を呼び出さないと何が表示されるのですか? – Leeor

+0

どのような要件、バランスのとれた木、ソートされたもの、何か他のですか? – danh

+0

ダンバランスツリー –

答えて

0

データを表示する前にバイナリツリーにデータを追加しようとしましたか?

新しい回答: データを次のように変更するようにコードを修正しました。私はそれはあなたが何にもあなたの一時を参照していなかったんでした

 1 
    2  3 
4 5 6 7 etc 

#include <conio.h> 
#include <stdlib.h> 
#include <stdio.h> 


struct node 
{ 
    int data; 
    struct node*left; 
    struct node*right; 
}; 

int i, parent; 
struct node*root = NULL; 
struct node*newnode, *temp[20]; 

void display(struct node *root) 
{ 
    if (root != NULL) { 
     printf("%d\t", root->data); 
     display(root->left); 
     display(root->right); 
    } 
} 

void add(int num) 
{ 
    for (i = 0; i<num; i++) 
    { 
     newnode = (struct node*)malloc(sizeof(struct node)); 
     newnode->left = newnode->right = NULL; 
     newnode->data = i + 1; 
     temp[i] = newnode; 
     if (i == 0) 
     { 
      root = newnode; 
      continue; 
     } 
     parent = (i - 1)/2; 

     if (i % 2 == 0) temp[parent]->right = newnode; 

     else temp[parent]->left = newnode; 


    } 
} 

int main() 
{ 
    int num; 
    printf("enter a binary number (Max 20):"); 
    scanf("%d", &num); 
    add(num); 
    display(root); 

} 

ミスをやろうとしているとサイズをprecisingせずに配列を定義し、何を願っています。

+0

はい、私は試しました。それでも同じです。 –

+0

私の答え@ NazifaTabassumを編集しました。私はそれが助けてくれることを願っています:) – Ismael123

0

このコードは:あなたはどんな条件なしcontinue文を書くため

parent=(i-1)/2; 

    if(i%2==0)temp[parent]->right=newnode; 

    else temp[parent]->left=newnode; 

、達していません。

+0

私は条件を変更してみましたが、結果は値だけに印刷されています。 –

関連する問題