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