I am solving Leetcode problem #94 for in-order traversal of a binary tree.
I cannot understand why - when I use &cpy
(currently commented) when calling helper()
the program works correctly but not when I use &gResult
.
int countNode(struct TreeNode* root)
{
if(root)
return 1 countNode(root->left) countNode(root->right);
return 0;
}
void helper(struct TreeNode* root, int** res)
{
if(root)
{
helper(root->left, res);
*((*res) ) = root->val;
helper(root->right, res);
}
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* inorderTraversal(struct TreeNode* root, int* returnSize){
int *gResult = NULL;
*returnSize = countNode(root);
gResult = (int*)malloc(((*returnSize)) * sizeof(int));
memset(gResult, 0, (*returnSize) * sizeof(int));
int *cpy = gResult;
// helper(root, &cpy);
helper(root, &gResult);
return gResult;
}
CodePudding user response:
The function helper
changes the value of the pointer passed to the function by reference.
*((*res) ) = root->val;
^^^^^^^^
So after calling the function the original pointer will not point to the allocated memory.
Thus using an intermediate pointer like in this code snippet
int *cpy = gResult;
helper(root, &cpy);
leaves the pointer gResult
unchanged that points to the dynamically allocated memory and is returned from the function inorderTraversal
. And the caller of the function can be able to free the allocated memory successfully using the returned pointer.