给定二叉树,返回所有根到叶路径

时间:2015-11-25 07:11:21

标签: c runtime binary-tree

我试图在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;
}

1 个答案:

答案 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