Q:

Preorder tree traversal function which returns an array of integers in C

I try to write a function which return an array of integers containing the node values of the binary tree in preorder that is a node value must appear before the values of its left and right child.

if root is NULL, return NULL
for every node left child comes before right child

For example;
int *a = preorder(bt1);
for (i=0; i<3; i++)
    printf("%d ", a[i]);
>2_1_3_

Here is my work, but it doesn't work, where could be the problem in my code?
int* preorder(TreeNode *root) {
    int *a = malloc(sizeof(int)*50);
    int i=0;

    if(root == NULL)
        return NULL;
    else {
        if(root != NULL) {
            a[i] = root->val;
            i++;
            preorder(root->left);
            preorder(root->right);
            return a;
        }
    }
}

A:

You have two issues in the code:

You have to allocate the array for results once. Before calling preorder
You have to keep i outside of preorder to allow it to change between calls

One example is the following code:
int *a = malloc(sizeof(int)*50);
int inx = 0;
preorder(bt1, a, &inx);

void preorder(TreeNode *root, int* a, int* inx) {
    if(root == NULL)
        return;
    else {
        if(root != NULL) {
            a[*inx] = root->val;
            *inx = *inx + 1;
            preorder(root->left, a, inx);
            preorder(root->right, a, inx);
        }
    }
}

