Skip to content

Commit ee49b6a

Browse files
authored
Update 437.path-sum-iii.md
1 parent 40c29aa commit ee49b6a

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

problems/437.path-sum-iii.md

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,8 @@ var pathSum = function (root, sum) {
117117

118118
## 代码
119119

120-
- 语言支持:JS
121-
120+
- 语言支持:JS,Python
121+
JS code:
122122
```js
123123
/*
124124
* @lc app=leetcode id=437 lang=javascript
@@ -163,6 +163,39 @@ var pathSum = function (root, sum) {
163163
return helper(root, 0, sum, hashmap);
164164
};
165165
```
166+
Python Code:
167+
```
168+
import collections
169+
from typing import *
170+
class TreeNode:
171+
def __init__(self, val=0, left=None, right=None):
172+
self.val = val
173+
self.left = left
174+
self.right = right
175+
176+
visited=collections.defaultdict(lambda:0) # only used for pathSum2
177+
acc=0
178+
179+
class Solution:
180+
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
181+
if not root:
182+
return 0
183+
global acc
184+
count=0
185+
acc+=root.val
186+
if acc==targetSum:
187+
count+=1
188+
if acc-targetSum in visited:
189+
count+=visited[acc-targetSum]
190+
visited[acc]+=1
191+
if root.left:
192+
count+=self.pathSum(root.left,targetSum)
193+
if root.right:
194+
count+=self.pathSum(root.right,targetSum)
195+
visited[acc]-=1
196+
acc-=root.val
197+
return count
198+
```
166199

167200
**复杂度分析**
168201

0 commit comments

Comments
 (0)