I am trying to implement an inorder traversal that returns an array with the traversed values. In my recursive approach, I am trying to use realloc()
function to modify the size of the array and store the result. However, I am getting the following error:
realloc(): invalid next size
.
Following is my code:
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void inorder(struct TreeNode *root, int *res, int *returnSize)
{
if(root == NULL)
return;
//if left node present, traverse left
inorder(root->left,res,returnSize);
// add node to array
res[(*returnSize)]=root->val;
(*returnSize)++;
int *temp = realloc(res,sizeof(int)*(*returnSize));
res = temp;
//if right node present, traverse right
inorder(root->right,res,returnSize);
}
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* inorderTraversal(struct TreeNode* root, int* returnSize)
{
//check if root == null
if(root == NULL)
{
return root;
}
//malloc result array to return
int *res = (int *)malloc(sizeof(int)*(*returnSize));
//start inorder parsing
inorder(root, res, returnSize);
return res;
}