[英]0 I'm working on a leetcode problem: Given the root of a binary tree, return the inorder traversal of its nodes' values
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:相反,将数组及其大小(地址)传递为 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.