You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
if root:
return self.findPath(root, sum)+self.pathSum(root.left, sum)+self.pathSum(root.right, sum)
return 0
def findPath(self, root, target):
if root:
return int(root.val==target)+self.findPath(root.left, target-root.val)+self.findPath(root.right, target-root.val)
return 0
1 基于每个节点traverse,找到其所有的paths to find if there is sum to target
2 root value 等于target值也是一种情况
3 从每一个节点开始往左右子节点走,使用recursive的方法,target-->target-root.val-->...直到target==当前节点value,就相当于找到了一个path,返回1;如果节点不存在了,就返回0;当走到某一个节点时,target==当前节点value,这时会返回1,但是此node的左右节点都还存在,还是会继续往下走的,直到走到叶子节点
4 所有的path,要包括以root为根节点开始的+root.left为根节点开始的+root.right为根节点开始的