马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 精简版,五行代码不解释
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
def dfs(root, sumlist):
if root is None: return 0
sumlist = [num + root.val for num in sumlist] + [root.val]
return sumlist.count(sum) + dfs(root.left, sumlist) + dfs(root.right, sumlist)
return dfs(root, [])
# 展开版,易理解
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
def dfs(root, sumlist):
if root is None:
return 0
sumlist = [num+root.val for num in sumlist]
sumlist.append(root.val)
count = 0
for num in sumlist:
if num == sum:
count += 1
# count = sumlist.count(sum)
return count + dfs(root.left, sumlist) + dfs(root.right, sumlist)
return dfs(root, [])
其中,[code]sumlist = [num+root.val for num in sumlist]
sumlist为空时,执行该列表推导式也为空是为什么
作者:Orust
链接:https://leetcode.cn/problems/pat ... ai-ma-yong-lie-bia/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。[/code] |