Click here to Skip to main content
15,886,781 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
/*I am trying to form a binary tree from an array of ints. The given code has some flaws.Please help 
in resolving them.I am using an array"addr[]" to store the addresses of various nodes according to 
their position in the tree.*/


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

typedef struct Node{
    int info;
    struct node *left;
    struct node *right;
}node;

void form_tree(int a[],node **root)
{
    int addr[100];
    int i;
    node *ptr;
    (*root)->info=a[0];
    (*root)->left=NULL;
    (*root)->right=NULL;
    addr[0]=-1;
    addr[1]=root;
    for(i=1;i<10;i++)
    {
        node *nw=(node*)malloc(sizeof(node));
        nw->info=a[i];
        nw->left=NULL;
        nw->right=NULL;
        addr[i+1]=&nw;
        ptr=addr[(i+1)/2];
        if((i+1)%2==0)
        ptr->left=&nw;
        else
        ptr->right=&nw;
    }   
}

int main()
{
    node *ptr;
    int a[10]={5,10,15,20,25,30,35,40,45,50};
    node *root;
    root=(node*)malloc(sizeof(node));
    form_tree(a,&root);
    ptr=root;
    while(ptr->left!=NULL)
    printf("\n%d",ptr->info); 
    getch();
}
Posted
Updated 25-May-13 0:29am
v6
Comments
OriginalGriff 25-May-13 6:47am    
"The given code has some flaws.Please help in resolving them."
This isn't very helpful! We can't see your screen, and without running your code we can't tell what you might consider a "flaw" - There are many, many things here that in a working environment I would consider totally unacceptable, but they probably aren't what you are having difficulties with! :laugh:

Tell us what problems you are having: What is it doing that it shouldn't, or not doing that it should?
Brady Bar 25-May-13 8:30am    
I am asking whether form_tree function is working or not.If not then what are the things that need to be changed.I am also not sure that the tree is being formed because the last printf statement is not printing the values on the leftmost path rooted at the starting vertex which in this case is the root of the tree.
OriginalGriff 25-May-13 8:44am    
Well, no - it won't.
while(ptr->left!=NULL)
printf("\n%d",ptr->info);
Either prints no values at all, or the same value over and over and over because you never change the value or ptr in the loop.
The functionality of the rest of it is a bit moot when your test code doesn't work either! :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900