2016-11-29 101 views
0

我試圖在編程c中實現二叉樹。它只取值但不顯示任何預期的結果。需要幫助來實現二叉樹。在這裏我添加了我的代碼,這個代碼正在嘗試很久。編程中的二叉樹實現代碼中的問題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

danh一棵平衡的樹 –

回答

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

} 

你做的錯誤是沒有引用你的臨時任何事情和定義一個數組,沒有預先確定的大小。

+0

是的,我試過了。但仍然相同。 –

+0

我編輯了我的答案@NazifaTabassum。我希望它可以幫助:) – Ismael123

0

此代碼:

parent=(i-1)/2; 

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

    else temp[parent]->left=newnode; 

沒有達到,因爲你寫continue聲明不附帶任何條件。

+0

我試圖通過改變條件,但結果只打印在價值。 –