题解 | #二叉树中和为某一值的路径(三)#

二叉树中和为某一值的路径(三)

http://www.nowcoder.com/practice/965fef32cae14a17a8e86c76ffe3131f

#coding:utf-8
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#

# @param root TreeNode类 
# @param sum int整型 
# @return int整型
#
class Solution:
    
    
    def __init__(self):
        self.d = dict()
        
    def findPath(self, root, s, last):
        if root is None:
            return 0
        res = 0
        temp = root.val + last
        if self.d.get(temp-s, None) != None:
            res += self.d.get(temp-s)
        if self.d.get(temp, None) != None:
            self.d[temp] += 1
        else:
            self.d[temp] = 1
        
        res += self.findPath(root.left, s, temp)
        res += self.findPath(root.right, s, temp)
        self.d[temp] -= 1
        return res
        
    def FindPath(self , root , sum ):
        # write code here
        self.d[0] = 1
        ret = self.findPath(root, sum, 0)
        return ret
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 12:20
点赞 评论 收藏
分享
不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务