Likou 437. Path Sum III (python)

Title source: 437. Path sum III
title: Given the root node root of a binary tree, and an integer targetSum, find the number of paths whose sum of node values ​​in the binary tree is equal to targetSum.

The path doesn't need to start at the root node, and it doesn't need to end at a leaf node, but the path direction must be down (only from parent to child).
insert image description here
insert image description here
Idea: The essence is whether to use the current node as the starting point. If it is the starting point, continue to move forward until the path sum is reached. If you don't go forward, traverse the left and right subtrees in turn, determine whether it is the starting point, and repeat until the path sum is found.
python code:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def pathSum(self, root, targetSum):
        """
        :type root: TreeNode
        :type targetSum: int
        :rtype: int
        """
        if not root:
            return 0
        return self.pathSum(root.left, targetSum) + self.pathSum(root.right, targetSum) + self.pathsumwithroot(root, targetSum)
    def pathsumwithroot(self, root, targetSum):
        if not root:
            return 0
        if root.val == targetSum:
            return 1 + self.pathsumwithroot(root.left, 0) + self.pathsumwithroot(root.right, 0)
        return self.pathsumwithroot(root.left, targetSum - root.val) + self.pathsumwithroot(root.right, targetSum - root.val)

insert image description here
Reference link: leetcode(62)_437_medium_path sum III_python

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324340647&siteId=291194637