Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
path-sum-iii.py 1.45 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-12-30 21:04 +08:00 . remove semicolons
# Time: O(n)
# Space: O(h)
import collections
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
def pathSumHelper(root, curr, sum, lookup):
if root is None:
return 0
curr += root.val
result = lookup[curr-sum] if curr-sum in lookup else 0
lookup[curr] += 1
result += pathSumHelper(root.left, curr, sum, lookup) + \
pathSumHelper(root.right, curr, sum, lookup)
lookup[curr] -= 1
if lookup[curr] == 0:
del lookup[curr]
return result
lookup = collections.defaultdict(int)
lookup[0] = 1
return pathSumHelper(root, 0, sum, lookup)
# Time: O(n^2)
# Space: O(h)
class Solution2(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
def pathSumHelper(root, prev, sum):
if root is None:
return 0
curr = prev + root.val
return int(curr == sum) + \
pathSumHelper(root.left, curr, sum) + \
pathSumHelper(root.right, curr, sum)
if root is None:
return 0
return pathSumHelper(root, 0, sum) + \
self.pathSum(root.left, sum) + \
self.pathSum(root.right, sum)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助