leetcode做题笔记113. 路径总和 II

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

思路一:递归

void dfs(struct TreeNode* root, int targetSum, int* returnSize, int** returnColumnSizes,int **returnNums,int *stack,int top,int sum)
{
    if(root == NULL)
    {
        return;
    }

    sum += root->val;
    stack[top]  = root->val;
    if(root->left== NULL && root->right == NULL)
    {
        if(sum == targetSum)
        {
           returnNums[*returnSize] = (int *)malloc(sizeof(int) * (top + 1));
           memcpy(returnNums[*returnSize] , stack, sizeof(int) * (top + 1));
            (*returnColumnSizes)[*returnSize] = top + 1;
            *returnSize = *returnSize + 1;
        }
    }
    dfs(root->left,targetSum,returnSize,returnColumnSizes,returnNums,stack,top+1,sum);
    dfs(root->right,targetSum,returnSize,returnColumnSizes,returnNums,stack,top+1,sum);
}

int** pathSum(struct TreeNode* root, int targetSum, int* returnSize, int** returnColumnSizes)
{
    int **returnNums = (int **)malloc(sizeof(int *)*50000);
    *returnColumnSizes = (int *)malloc(sizeof(int )*50000);
    *returnSize = 0;
    int stack[5000] = {0};
    dfs(root,targetSum,returnSize,returnColumnSizes,returnNums,stack,0,0);
    return returnNums;
}

分析:

本题要求路径总和,可想到将每个数到叶子节点的路径总和,等到叶子节点时判断总和是否等于目标数,用数组记录,最后输出答案即可,注意递归时注意用top记录栈顶位置

总结:

本题考察递归的应用,将路径中所有符合节点记录再输出即可

你可能感兴趣的:(二叉树,递归,leetcode,笔记,算法)