leetcode437 -- Path Sum III

leetcode437 -- Path Sum III

题目



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

这个题比之前的要难一些,现在的路径可以是中间的其中的一段都是可以的。


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> int:
        if not root:
            return 0
        res = []
        self.helper(root, sum , 0, res, [])
        print(res)
        return len(res)
     
    def helper(self, root, target, curSum, res, out):
        if not root:
            return
        
        curSum += root.val
        out.append(root.val)
        
        if curSum == target:
            res.append(out[:])
        
        temp = curSum
        for i in range(len(out)-1):  ## 这是要看去掉一些能不能行,要保留一个。
            temp -= out[i]
            Temp = out[:]
            del(Temp[i])
            if temp == target:
                res.append(Temp)
        self.helper(root.left, target, curSum, res,out[:])
        self.helper(root.right, target, curSum, res, out[:])
        out.pop()
        
        

上面的解法我是想找到的同时把路径也保存下来

如果不保存结果的话

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> int:
        if not root:
            return 0
        
        return self.helper(root, sum , 0, 0, [])
        
     
    def helper(self, root, target, curSum, res, out):
        if not root:
            return res  # 注意这里是返回res.
        
        curSum += root.val
        out.append(root.val)
        
        if curSum == target:
            res += 1
        
        temp = curSum
        for i in range(len(out)-1):
            temp -= out[i]
            Temp = out[:]
            del(Temp[i])
            if temp == target:
                res += 1
                
        res = self.helper(root.left, target, curSum, res,out[:])
        res = self.helper(root.right, target, curSum, res, out[:])
        out.pop()
        return res 
        
        

打赏,谢谢~~

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,多谢支持~

打开微信扫一扫,即可进行扫码打赏哦