加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

leetcode113 - path sum II - medium

发布时间:2020-12-14 05:06:27 所属栏目:大数据 来源:网络整理
导读:Given a binary tree and a sum,find all root-to-leaf paths where each path‘s sum equals the given sum. Note:?A leaf is a node with no children. Example: Given the below binary tree and? sum = 22 , 5 / 4 8 / / 11 13 4 / / 7 2 5 1 Return:

Given a binary tree and a sum,find all root-to-leaf paths where each path‘s sum equals the given sum.

Note:?A leaf is a node with no children.

Example:

Given the below binary tree and?sum = 22,

      5
     /     4   8
   /   /   11  13  4
 /      / 7    2  5   1

Return:

[
   [5,4,11,2],[5,8,5]
]
思路:这题和112是姐妹题。112只需要判断是否有path sum,113需要返回path sum。在这类题中,我经常会犯的一个错误是对于Nontype的判断,经常会出现Nonetype没有left或者right的报错。
以及这题需要注意的是一定会需要用到children的值,如果有children的话,不能是我自己的值符合sum了,这样就应该是错的。所以比较好的方法是 if not root.right and not root.left and root.val == sum: return True
class Solution:
    def pathSum(self,root: TreeNode,sum: int) -> List[List[int]]:
        ans = []
        if not root: return ans
        self.help(root,ans,[],sum)
        return ans
    
    
    def help(self,root,path,sum):
        if not root:
            return ans
        if not root.left and not root.right and root.val == sum:
            ans.append(path+[root.val])
        self.help(root.left,path+[root.val],sum-root.val)
        self.help(root.right,sum-root.val)
        return ans

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读