【Leetcode】437. Path Sum III

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为根节点开始的

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,068评论 0赞 10
  • 上海有家杂志,在北京、上海、南京、武汉、成都、杭州做了调查之后便推出一个“六城市居民幸福指数”。如果我们参照上海那...
    li成林阅读 849评论 4赞 3
  • 感觉自己被孤独淹没,便随手抓住了一根自以为是救命的稻草。谁知道,被那根稻草带去的世界,却是邪恶的。想要松手,可就要...
    Sonia_a853阅读 152评论 0赞 0

友情链接更多精彩内容