The sum of the path 437 III

Title: Given a binary tree, each node that are stored with an integer value. Total number of paths to find the path and is equal to the given value. Path does not require starting from the root, do not need to end in a leaf node, but the path direction must be down (only node from parent to child node).
Source: https://leetcode-cn.com/problems/path-sum-iii/

Act one: their own code, the code expires, because when computing res, and with no previous results, but every time recalculated again, the results of this calculation must take the time to be passed as a parameter, each pair there are several parameters were calculated in line with the results. will greatly reduce the number of calculations

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        selfval = the x
        self.left = None
        self.right = None
class Solution:
    def pathSum(self, root: TreeNode, su: int) -> int:
        results = [0]
        def judge(res):
            a = []
            while res:
                a.append(res.pop())
                if sum(a) == su:
                    results[0] = results[0] + 1
        def recursion(root,res):
            if root is None:
                return
            res.append(root.val)
            # Each time of determination summing res 
            judge (res [:])
            recursion(root.left, res)
            recursion(root.right, res)
            res.pop()
        recursion(root,res=[])
        return results[0]
View Code

Improved code does not time out,

# Execute when used: 180 ms, beat the 93.22% of users in all python3 submission 
# memory consumption: 33.4 MB, beat the 9.56% of users in all python3 submission 
class Solution:
     DEF pathSum (Self, root: TreeNode, su: int) -> int:
        Results = [0]
         DEF recursion (root, res):
             IF root IS None:
                 return 
            # first calculate a few meet the conditions, and transmits res must not first pass after the last calculation, in which case a step slow,. 
            res = [ + I root.val for I in RES] + [root.val]
            Results [0] = Results [0] + res.count (SU)
             # RES is a variable object and is passed directly transmitted, but the res = [root.val + i for i in res] + [root.val ] 
            # in the res for re-assignment, so after the end of the function call, the content did not change res 
            recursion (root.left, res)
            recursion(root.right,res)
        recursion(root,res=[])
        return results[0]
if __name__ == '__main__':
    duixiang = Solution ()
    root = TreeNode(5)
    a = TreeNode(4)
    b = TreeNode(11)
    c = TreeNode(2)
    d = TreeNode(2)
    root.left = a
    a.left = b
    b.left = c
    b.right = d
    SU = 22 is 
    A = duixiang.pathSum (the root, SU)
     Print (A)
View Code

 

Guess you like

Origin www.cnblogs.com/xxswkl/p/12002884.html