Search code examples
cbinary-tree

Create a binary tree using an array of elements


So im trying to create a binary tree using a given array and then print the results in order,preorder and postorder but it seems i have done a mistake somewhere but as far as i can see things should be ok.

This is the result it prints out

1 2 3 4 5 6 7 8 9 10  #inorder
10 9 8 7 6 5 4 3 2 1  #postorder
1 2 3 4 5 6 7 8 9 10  #preorder

this is what ive done so far. Can somebody point out the mistake and maybe an advice on how to fix it?

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

typedef struct node_s node_t;
struct node_s
{
    int key;
    node_t *left,*right;
};
node_t *new_node(int val)
{
    node_t *new;
    new= malloc(sizeof (node_t));
    if(new==NULL)
    {
        exit(1);
    }
    new->key=val;
    new->left=NULL;
    new->right=NULL;
    return new;
}
void print_inorder(node_t *root)
{
    node_t *new=root;
    if (new != NULL) {
        print_inorder(new->left);
        printf("%d ",new->key);
        print_inorder(new->right);
    }
    return;

}
void print_postorder(node_t *root)
{
    node_t *new=root;
    if (new != NULL) {
        print_postorder(new->left);
        print_postorder(new->right);
        printf("%d ",new->key);
    }
    return;

}
void print_preorder(node_t *root)
{
    node_t *new=root;
    if (new != NULL) {
        printf("%d ",new->key);
        print_preorder(new->left);
        print_preorder(new->right);
    }
    return;

}
node_t *insert_node(node_t *root,int val)
{
     if(root==NULL)
            return new_node(val);
     else
     {
         if(val<root->left)
             root->left= insert_node(root->left,val);
         else if(val>root->left)
             root->right= insert_node(root->right,val);
     }
    return root;
}
int main() {

    int n;
    int v[]={1,2,3,4,5,6,7,8,9,10};
    node_t *root=NULL;
    FILE *file;
    file= fopen("file","r");
    if(file==NULL)
    {
        exit(1);
    }
    for (int i = 0; i < 10; ++i) {
        root= insert_node(root,v[i]);
    }

    print_inorder(root);
    printf("\n");
    print_postorder(root);
    printf("\n");
    print_preorder(root);

    return 0;
}

Solution

  • Save time, enable all compiler warnings.

    Problems identified in seconds!
    Code has at least this problem:

    Compare between integer and pointer

    // warning: comparison between pointer and integer
    if (val < root->left) // Bad
    

    Likely wanted:

    if (val < root->key)
    

    Likewise with else if (val > root->left)