int *arr=NULL;
int size=0;
void inorder (struct TreeNode *root)
{
if(root)
{
inorder(root->left);
arr=(int *)realloc(arr,sizeof(int)*(++size));
arr[size-1]=root->val;
inorder(root->right);
}
}
int* inorderTraversal (struct TreeNode* root, int* returnSize)
{
inorder(root);
*(returnSize)=size;
return arr;
}
// I don't understand what's the mistake I have done, but it's giving me wrong answer. Test cases when run are passed successfully but during submission "Wrong Answer" Pops up. Can anybody help me solve this please?
You should not use global variables for this: their values will be retained from one test to the next, and so a subsequent test will start with the array values left by the previous run.
Instead, pass (the address of) the array and its size as arguments:
void inorder (struct TreeNode *root, int **arr, int *size)
{
if (root)
{
inorder(root->left, arr, size);
*arr = (int *)realloc(*arr, sizeof(int)*(++*size));
(*arr)[*size - 1] = root->val;
inorder(root->right, arr, size);
}
}
int* inorderTraversal (struct TreeNode* root, int* returnSize)
{
int *arr = NULL;
*returnSize = 0;
inorder(root, &arr, returnSize);
return arr;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.