我试图在c中的leetcode上解决这个问题 https://leetcode.com/problems/binary-tree-paths/。 该代码适用于小型测试用例。但对于较大的那些,它显示运行时错误。我试过增加阵列的大小,但无济于事。请帮忙。
程序失败的测试用例是:
[ - 64,12,18,-4,-53,空,76,空,-51,NULL,NULL,-93,3,NULL,-31,47,NULL,3,53,-81 ,33,4,NULL,-51,-44,-60,11,NULL,NULL,NULL,NULL,78,空,-35,-64,26,-81,-31,27,60,74, NULL,NULL,8,-38,47,12,-24,NULL,-59,-49,-11,-51,67,NULL,NULL,NULL,NULL,NULL,NULL,NULL,-67,空,-37,-19,10,-55,72,NULL,NULL,NULL,-70,17,-4,NULL,NULL,NULL,NULL,NULL,NULL,NULL,3,80,44,-88 ,-91,空,48,-90,-30,NULL,NULL,90,-34,37,NULL,NULL,73,-38,-31,-85,-31,-96,NULL,NULL, -18,67,34,72,NULL,-17,-77,空,56,-65,-88,-53,NULL,NULL,NULL,-33,86,空,81,-42,空空,98,-40,70,-26,24,NULL,NULL,NULL,NULL,92,72,-27,NULL,NULL,NULL,NULL,NULL,NULL,-67,NULL,NULL,NULL, NULL,NULL,NULL,NULL,-54,-66,-36,NULL,-72,NULL,NULL,43,NULL,NULL,NULL,-92,-1,-98,NULL,NULL,NULL,NULL ,NULL,NULL,NULL,39,-84,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,-93,NULL,NULL,NULL,98] < / p>
int height(struct TreeNode* root){
if(root == NULL)
return 0;
if(root->left == NULL && root->right == NULL)
return 1;
int left = height(root->left);
int right = height(root->right);
return left> right? left+1: right+1;
}
void util(char **result, struct TreeNode* root, int i, int *r, char* temp){
i+= sprintf(temp+i, "%d", root->val);
printf("%d ",*r);
if(!root->left && !root->right){
sprintf(result[(*r)++],"%s", temp);
}
i+= sprintf(temp+i, "->");
if(root->left){
util(result, root->left, i, r, temp);
}
if(root->right){
util(result, root->right, i, r, temp);
}
}
char** binaryTreePaths(struct TreeNode* root, int* returnSize) {
if(root == NULL)
return NULL;
int ht = height(root);
int width = pow(2,ht-1);
char **result = malloc((width+1)* sizeof(char *));
int i, r=0;
char *temp = malloc((height+1)* sizeof(char));
for(i=0; i<=ht; i++)
result[i] = malloc((height+1) * sizeof(char));
util(result, root, 0, &r, temp);
*returnSize = r;
return result;
}
答案 0 :(得分:0)
temp
数组和result
中的每个条目都应分配给更大的大小:它必须能够保存height+1
十进制的整数值+2个字符+一个最终'\0'
1}}。 height+1
太小了。
假设32位整数,请尝试:
int length = (ht + 1) * 12;
char *temp = malloc(length);
for (i = 0; i <= ht; i++)
result[i] = malloc(length);
您可以通过分配存储在result
数组中的每个路径来减少使用的内存量。为此,请从for
移除上面的binaryPaths
循环,然后修改util
中存储路径的result
中的行:
if (!root->left && !root->right) {
result[(*r)++] = strdup(temp);
}
这是一种更好的方法,因为您不返回实际分配的大小而只返回路径数,因此result
中的额外条目将无法访问且无法释放。
请记得在从temp
返回之前免费binaryTreePaths
。