leetcode-113 🐛🐛🐛
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
/** * 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(). */ //有昨天那道题 写的挺快的 就是leetcode吞我代码 不就是骂你了嘛 嘤嘤嘤 void digui(struct TreeNode* root,int targetSum,int arr[],int **returns,int* returnSize,int index,int **returnColumnSizes) { if(root == NULL) return; arr[index] = root->val; targetSum -= root->val; //这里注意 已经将新的结点值加入了数组中 下面开辟内存时要+1 if(targetSum == 0 && root->left == NULL && root->right == NULL) //递归end condition { returns[(*returnSize)] = (int *)calloc((index+1),sizeof(int ));//这里 这里哦 for(int i = 0;i <= index;i++) { returns[(*returnSize)][i] = arr[i]; } (*returnColumnSizes)[*returnSize] = index+1; //这句留着 哎 咱没想到哇 (*returnSize)++; return; } digui(root->left,targetSum,arr,returns,returnSize,index+1,returnColumnSizes); digui(root->right,targetSum,arr,returns,returnSize,index+1,returnColumnSizes); // index--; 我又没加 不用减啦 return ; } int** pathSum(struct TreeNode* root, int targetSum, int* returnSize, int** returnColumnSizes){ *returnSize = 0; *returnColumnSizes = (int *)malloc(sizeof(int)*5050); //这句留着 哼 int **returns = (int **)malloc(sizeof(int *)*5050); int *arr = (int *)malloc(sizeof(int)*5050); int index = 0; digui(root,targetSum,arr,returns,returnSize,index,returnColumnSizes); //递归出发! root开始 ya我从root->left开始 我输出了 前缀和?ahhhh (bushi return returns; }