Build a binary tree from an array of elements

I’m trying to create a binary tree and print the results in in-order, post-order, and pre-order traversal, but I’m getting unexpected results. This is the code I have so far:

#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;
}

I’m getting the following output:

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

Does anyone see any mistakes in my code that would cause these results? Any advice on how to fix it?

The issue in your code lies in the insert_node function. You are comparing the val parameter with root->left instead of root->key. Here is the corrected code:

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

By comparing val with root->key, the nodes will be inserted correctly in the binary tree.

After making this change, you should get the expected output:

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