File tree Expand file tree Collapse file tree 1 file changed +35
-2
lines changed Expand file tree Collapse file tree 1 file changed +35
-2
lines changed Original file line number Diff line number Diff line change @@ -117,8 +117,8 @@ var pathSum = function (root, sum) {
117
117
118
118
## 代码
119
119
120
- - 语言支持:JS
121
-
120
+ - 语言支持:JS,Python
121
+ JS code:
122
122
``` js
123
123
/*
124
124
* @lc app=leetcode id=437 lang=javascript
@@ -163,6 +163,39 @@ var pathSum = function (root, sum) {
163
163
return helper (root, 0 , sum, hashmap);
164
164
};
165
165
```
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
+ ```
166
199
167
200
** 复杂度分析**
168
201
You can’t perform that action at this time.
0 commit comments