Skip to content

Commit 68a475f

Browse files
author
whd
committed
upload
1 parent 80065f2 commit 68a475f

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

437 Path Sum III .py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode(object):
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
class Solution(object):
9+
def pathSum(self, root, sum):
10+
"""
11+
:type root: TreeNode
12+
:type sum: int
13+
:rtype: int
14+
"""
15+
ans = 0
16+
dic = {}
17+
dic[0] = 1
18+
global ans
19+
def dfs(x, now):
20+
global ans
21+
if not x:
22+
return
23+
now += x.val
24+
if (now - sum) in dic:
25+
ans += dic[now - sum]
26+
if not now in dic:
27+
dic[now] = 0
28+
dic[now] += 1
29+
dfs(x.left, now)
30+
dfs(x.right, now)
31+
dic[now] -= 1
32+
33+
dfs(root, 0)
34+
return ans

0 commit comments

Comments
 (0)