[LeetCode] 437. Path Sum III

题:https://leetcode.com/problems/path-sum-iii/description/

题目

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1
Return 3. The paths that sum to 8 are:

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

思路

题目分析

二叉树中,选取一个节点和它子节点,若从该节点到其子节点所有节点之和为 sum。那么视为 一条成功的路径。
给定一个 二叉树 和 sum,统计出 成功路径 的个数。

解题思路

分两步:
第一步:对于 一个作为起点的节点,它有所有子节点组成的成功路径有多少。
第二步:计算 每个节点 为起点的 成功路径,然后求和。

给定一个根节点 计算 它到每个子节点时所经过所有节点上 val的和。
代码可以为 dfs 。

第一步

def dfs(root,remainder):
    if root == None:
        return 0
    res = 0
    if root.val == remainder:
        res += 1
    return res + dfs(root.left,remainder - root.val) + dfs(root.right,remainder - root.val)

第二步

    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        if root == None:
            return 0
        return dfs(root,sum)+self.pathSum(root.left,sum)+self.pathSum(root.right,sum)

code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
def dfs(root,remainder):
    if root == None:
        return 0
    res = 0
    if remainder == root.val:
        res += 1
    return res+dfs(root.left,remainder - root.val) + dfs(root.right,remainder - root.val)
class Solution:
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        if root == None:
            return 0
        return dfs(root,sum)+self.pathSum(root.left,sum)+self.pathSum(root.right,sum)

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/82154147