標籤:count 父節點 red lse bsp root div 方向 pre
問題描述:
給定一個二叉樹,它的每個結點都存放著一個整數值。
找出路徑和等於給定數值的路徑總數。
路徑不需要從根節點開始,也不需要在葉子節點結束,但是路徑方向必須是向下的(只能從父節點到子節點)。
二叉樹不超過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 -> 32. 5 -> 2 -> 13. -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 011 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 016 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=010 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.val17 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]+=121 else:22 self.d[csum]=123 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.val13 self.count += preDict.get(pathSum - target, 0)14 preDict[pathSum] = preDict.get(pathSum, 0) + 115 dfs(p.left, target, pathSum, preDict)16 dfs(p.right, target, pathSum, preDict)17 preDict[pathSum] -= 118 dfs(root, target, 0, preDict)19 return self.count20
2018-10-02 20:04:13
LeetCode--437--路徑總和3