赞
踩
记录前缀和的解法,一开始只想到了暴力解法
class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: int """ self.cnt=0 currsum=0 self.presumlist=[] def rec(root,sum,currsum): if not root: return self.cnt currsum+=root.val if currsum==sum: self.cnt+=1 for presum in self.presumlist: if currsum-presum==sum: self.cnt+=1 self.presumlist.append(currsum) rec(root.left,sum,currsum) # print(self.presumlist) rec(root.right,sum,currsum) self.presumlist.pop() return self.cnt return rec(root,sum,currsum)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。