数据结构(六十三)
学习数据结构与算法过程中的心得体会以及知识点的整理,方便我自己查找,也希望可以和大家一起交流。
—— 二叉树中和为某一值的路径 ——
1.题目描述
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
示例
输入:
root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:
[[5,4,11,2],[5,8,4,5]]
2.代码
c
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* 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 bk[1001];
void dfs(struct TreeNode *node, int target, int *returnSize, int **returnColumnSizes, int ans, int cnt, int **ret)
{
if (node == NULL)
return;
ans += node->val;
bk[cnt++] = node->val;
if (node->right == NULL && node->left == NULL) {
if (ans == target) {
(*returnColumnSizes)[*returnSize] = cnt;
memcpy(ret[(*returnSize)++], bk, sizeof(int) * cnt);
}
return;
}
if (node->left)
dfs(node->left, target, returnSize, returnColumnSizes, ans, cnt, ret);
if (node->right)
dfs(node->right, target, returnSize, returnColumnSizes, ans, cnt, ret);
}
int** pathSum(struct TreeNode* root, int target, int* returnSize, int** returnColumnSizes){
int **ans = malloc(sizeof(int *) * 300);
for (int i = 0; i < 300; i++)
ans[i] = malloc(sizeof(int) * 1000);
(*returnSize) = 0;
(*returnColumnSizes) = malloc(sizeof(int) * 1000);
dfs(root, target, returnSize, returnColumnSizes, 0, 0, ans);
return ans;
}
这题挺难的,我也是看了题解和大佬的思路才明白怎么实现回溯,运用的思想不难,但是实现起来,受限于C语言本身的问题,对指针的操作很容易出错。