Leetcode 113. Path Sum II

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

For 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 class Solution(object):
 2     def pathSum(self, root, sum):
 3         """
 4         :type root: TreeNode
 5         :type sum: int
 6         :rtype: List[List[int]]
 7         """
 8         res = []
 9         self.helper(root, sum, res, [])
10         
11         return res
12     
13     def helper(self, root, sum, res, path):
14         if not root:
15             return 
16         
17         if not root.left and not root.right and root.val == sum:
18             path.append(root.val)
19             res.append([x for x in path])
20             return 
21         
22         self.helper(root.left, sum - root.val, res, path + [root.val])
23         self.helper(root.right, sum - root.val, res, path + [root.val])
24         return 


上面的解法由于在L22和L23中没有重新定义path,所以可以不用pop。如果重新定义path,可用如下解法。这二者的区别类似 Binary tree path 一题中 九章算法和书影的给出的解法的区别。

 1 class Solution(object):
 2     def pathSum(self, root, sum):
 3         """
 4         :type root: TreeNode
 5         :type sum: int
 6         :rtype: List[List[int]]
 7         """
 8         res = []
 9         self.helper(root, sum, res, [])
10         
11         return res
12     
13     def helper(self, root, sum, res, path):
14         if not root:
15             return 
16         
17         if not root.left and not root.right and root.val == sum:
18             path.append(root.val)
19             res.append([x for x in path])
20             return 
21         
22         self.helper(root.left, sum - root.val, res, path + [root.val])
23         self.helper(root.right, sum - root.val, res, path + [root.val])
24         return 

 

posted @ 2016-12-27 11:01  lettuan  阅读(123)  评论(0)    收藏  举报