I'm trying to do a function that inserts values into a binary tree. The first while loop in insertbin(...) just completely ignores the x value when it's equal to NULL after it has been moved to the next element. Is there something wrong in my condition?
I've tried using a prev node to check the condition but it still didn't work.
#include <stdlib.h>
#include <stdio.h>
#include "Queue_arr.h"
tree* createtree() {
    tree*mytree = (tree*)malloc(sizeof(tree));
    mytree->root = NULL;
    return mytree;
}
void insertbin(tree* T, int data) {
    treenode *x, *y, *z;
    int flag = 1;
    z = (treenode*)malloc(sizeof(treenode));
    y = NULL;
    x = T->root;
    z->key = data;
    while (x != NULL) //While the tree isn't empty
    {
        y = x;
        if (z->key < x->key) //If the data is smaller than the existing key to the left
            x = x->sonleft;
        else //Else, to the right
            x = x->sonright;
    }
    z->father = y;
    if (y == NULL) //If y is the root
        T->root = z;
    else
        if (z->key < y->key) //If the data is smaller than the existing key to the left
            y->sonleft = z;
        else //Else, to the right
            y->sonright = z;
}
void insertscan(tree *T) //Scans the data to insert to the tree via insertbin(...)
{
    int data;
    printf("Enter a number (Enter a negative number to stop): \n");
    scanf("%d", &data);
    while (data >= 0)
    {
        insertbin(T, data);
        scanf("%d", &data);
    }
}
void main()
{
    tree* T;
    T = createtree();
    insertscan(T);
}
