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

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

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
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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