Problem Description:
Given a binary tree, each of its nodes holds an integer value.
Find the path and the total number of paths equal to the given number.
The path does not need to start from the root node, nor does it need to end at the leaf node, but the path direction must be down (from the parent node to the child node only).
A binary tree does not exceed 1000 nodes, and the value range of the node is an integer of [ -1000000,1000000].
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 / 5 -3 /\ \ 3 2 /\ \3 -2 1 returns 3. and the paths equal to 8 are: 1. 5. 5, 2. -3-11
Method 1:
1 classsolution (object):2 defpathsum (self, Root, sum):3 """4 : Type Root:treenode5 : Type Sum:int6 : Rtype:int7 """8 defDFS (root,sum):9 ifRoot = =None:Ten return0 One ifRoot.val = =sum: A return1 + DFS (root.left,0) +dfs (root.right,0) - returnDFS (Root.left,sum-root.val) + DFS (Root.right,sum-root.val) - ifRoot = =None: the return0 - returnDFS (Root,sum) + self.pathsum (root.left,sum) + self.pathsum (root.right,sum)
Method 2:
1 classsolution (object):2 defpathsum (self, Root, sum):3 """4 : Type Root:treenode5 : Type Sum:int6 : Rtype:int7 """8self.sum=sum9self.result=0TenSelf.d={0:1} One self.f (root,0) A return(Self.result) - - deff (self,root,csum): the if(root!=None): -csum+=Root.val - if((Csum-self.sum)inchself.d): -self.result+=self.d[csum-Self.sum] + if(Csuminchself.d): -Self.d[csum]+=1 + Else: ASelf.d[csum]=1 at self.f (root.left,csum) - self.f (root.right,csum) -Self.d[csum]-=1
Method 3:
1 classsolution (object):2 defpathsum (self, root, target):3 """4 : Type Root:treenode5 : Type Target:int6 : Rtype:int7 """8Self.count =09PreDict = {0:1}Ten defDFS (p, Target, Pathsum, preDict): One ifP: APathsum + =P.val -Self.count + = Predict.get (Pathsum-target, 0) -Predict[pathsum] = predict.get (pathsum, 0) + 1 the DFS (P.left, Target, Pathsum, preDict) - DFS (p.right, Target, Pathsum, preDict) -Predict[pathsum]-= 1 - DFS (root, target, 0, preDict) + returnSelf.count -
2018-10-02 20:04:13
leetcode--437--Path Sum 3