[LeetCode] 437. 路径总和 III (递归,二叉树)

Posted coding-gaga

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 437. 路径总和 III (递归,二叉树)相关的知识,希望对你有一定的参考价值。

题目

给定一个二叉树,它的每个结点都存放着一个整数值。

找出路径和等于给定数值的路径总数。

路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。

示例:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

  10
 /  5   -3

/ ? 3 2 11
/ ? 3 -2 1

返回 3。和等于 8 的路径有:

  1. 5 -> 3
  2. 5 -> 2 -> 1
  3. -3 -> 11

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

  • 两层递归:
  • 内层递归函数计算每个节点为根结点的字数路径和与给定值相等的路径个数,内层递归是在最后一个累加数时+1的。
  • 外层递归函数=内层递归函数(root)+外层递归函数(root.left)+外层递归函数(root.right),理清外层递归函数的这个逻辑。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int pathSum(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        return partialCnt(root, sum) + partialCnt(root.left, sum) + partialCnt(root.right, sum);//
    }

    public int partialCnt(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        return (sum == root.val ? 1 : 0) + partialCnt(root.left, sum - root.val)
                + partialCnt(root.right, sum - root.val);//
    }
}

以上是关于[LeetCode] 437. 路径总和 III (递归,二叉树)的主要内容,如果未能解决你的问题,请参考以下文章

*Leetcode 437. 路径总和 III

[LeetCode] 437. 路径总和 III ☆☆☆(递归)

LeetCode 437. 路径总和 III Path Sum III (Easy)

leetcode 437. 路径总和 III

leetcode 437. 路径总和 III(Path Sum III)

[LeetCode] 437. 路径总和 III (递归,二叉树)