难度: Easy
原题连接
内容描述
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,4,5]
]
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******
注意宁愿写几次curList + [root.val] 也不要直接传一个list进去,因为list pass by reference的亏已经吃过了
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
res = []
self.auxPathSum(root, sum, [], res)
return res
def auxPathSum(self, root, sum, cur_list, cur_lists):
if not root:
return
sum -= root.val
if sum == 0 and not root.left and not root.right:
cur_lists.append(cur_list + [root.val])
return
if root.left:
self.auxPathSum(root.left, sum, cur_list + [root.val], cur_lists)
if root.right:
self.auxPathSum(root.right, sum, cur_list + [root.val], cur_lists)