Guest User

Untitled

a guest
Oct 20th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
  2.  
  3. For example:
  4. Given the below binary tree and sum = 22,
  5. 5
  6. / \
  7. 4 8
  8. / / \
  9. 11 13 4
  10. / \ / \
  11. 7 2 5 1
  12. return
  13. [
  14. [5,4,11,2],
  15. [5,8,4,5]
  16. ]
  17.  
  18. # 1.
  19. # Definition for a binary tree node.
  20. # class TreeNode(object):
  21. # def __init__(self, x):
  22. # self.val = x
  23. # self.left = None
  24. # self.right = None
  25.  
  26. class Solution(object):
  27. def pathSum(self, root, sum):
  28. """
  29. :type root: TreeNode
  30. :type sum: int
  31. :rtype: List[List[int]]
  32. """
  33. if not root:
  34. return []
  35. if not root.left and not root.right and sum == root.val:
  36. return [[root.val]]
  37. tmp = self.pathSum(root.left, sum-root.val) + self.pathSum(root.right, sum-root.val)
  38. return [[root.val]+i for i in tmp]
  39. #2.
  40. def pathSum(self, root, sum):
  41. """
  42. :type root: TreeNode
  43. :type sum: int
  44. :rtype: List[List[int]]
  45. """
  46. if not root:
  47. return []
  48. pl = []
  49. self.path(root, sum, [], pl)
  50. return pl
  51.  
  52. def path(self, root, sum, onePath, pl):
  53. if not root.left and not root.right and root.val == sum:
  54. onePath.append(root.val)
  55. pl.append(onePath)
  56. if root.left:
  57. self.path(root.left, sum-root.val, onePath+[root.val],pl)
  58. if root.right:
  59. self.path(root.right, sum-root.val, onePath+[root.val],pl)
Add Comment
Please, Sign In to add comment