【
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
】
112题的升级版,这题二叉树题需要把路径给记录下来,需要一个temp数组。这题有点容易出错。深搜传参太多了。
void preorder(struct TreeNode* root, int sum, int *size, int* colsize, int **result, int *temp, int now) {
int i;
if(root == NULL) return;
if((root->left==NULL) && (root->right == NULL) && (sum == root->val)) {
temp[now++] = root->val;
colsize[*size] = now;
result[*size] = (int *)malloc(sizeof(int) * now);
for(i = 0; i < now; i++) {
result[*size][i] = temp[i];
}
(*size)++;
}
temp[now++] = root->val;
sum -= root->val;
preorder(root->left, sum, size, colsize, result, temp, now);
preorder(root->right, sum, size, colsize, result, temp, now);
}
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** pathSum(struct TreeNode* root, int sum, int* returnSize, int** returnColumnSizes){
int **result;
int size = 0;
int *colsize;
int temp[1024] = {0};
result = (int **)malloc(sizeof(int *) * 1024);
colsize = (int *)malloc(sizeof(int *) * 1024);
preorder(root, sum, &size, colsize, result, temp, 0);
*returnSize = size;
*returnColumnSizes = colsize;
return result;
}