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;
}
}
}
preorderis storing the result into a different array. That is clearly not what you want. You need to pass the array to eachpreordercall. - kaylum