LeetCode--437--路径总和3

问题描述:

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

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

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

二叉树不超过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

方法1:

 1 class Solution(object):
 2     def pathSum(self, root, sum):
 3         """
 4         :type root: TreeNode
 5         :type sum: int
 6         :rtype: int
 7         """
 8         def dfs(root,sum):
 9             if root == None:
10                 return 0
11             if root.val == sum:
12                 return 1 + dfs(root.left,0) + dfs(root.right,0)
13             return dfs(root.left,sum - root.val) + dfs(root.right,sum - root.val)
14         if root == None:
15             return 0
16         return dfs(root,sum) + self.pathSum(root.left,sum) + self.pathSum(root.right,sum)

方法2:

 1 class Solution(object):
 2     def pathSum(self, root, sum):
 3         """
 4         :type root: TreeNode
 5         :type sum: int
 6         :rtype: int
 7         """
 8         self.sum=sum
 9         self.result=0
10         self.d={0:1}
11         self.f(root,0)
12         return(self.result)
13     
14     def f(self,root,csum):
15         if(root!=None):
16             csum+=root.val
17             if((csum-self.sum) in self.d):
18                 self.result+=self.d[csum-self.sum]
19             if(csum in self.d):
20                 self.d[csum]+=1
21             else:
22                 self.d[csum]=1
23             self.f(root.left,csum)
24             self.f(root.right,csum)
25             self.d[csum]-=1

方法3:

 1 class Solution(object):
 2     def pathSum(self, root, target):
 3         """
 4         :type root: TreeNode
 5         :type target: int
 6         :rtype: int
 7         """
 8         self.count = 0
 9         preDict = {0: 1}
10         def dfs(p, target, pathSum, preDict):
11             if p:
12                 pathSum += p.val
13                 self.count += preDict.get(pathSum - target, 0)
14                 preDict[pathSum] = preDict.get(pathSum, 0) + 1
15                 dfs(p.left, target, pathSum, preDict)
16                 dfs(p.right, target, pathSum, preDict)
17                 preDict[pathSum] -= 1
18         dfs(root, target, 0, preDict)
19         return self.count
20         

2018-10-02 20:04:13

原文地址:https://www.cnblogs.com/NPC-assange/p/9737955.html