代码改变世界

[LeetCode] 113. Path Sum II

2018-07-14 00:49  Johnson_强生仔仔  阅读(294)  评论(0编辑  收藏  举报

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]
]

08/07/2018 update: 将node, path, pathsum 一起append进入stack.


这个题目实际上就跟[LeetCode] 257. Binary Tree Paths_ Easy tag: DFS, 思路一样, 只是加了个判断, path sum是否等于target sum而已.


1. Constraints
1) empty => []
2) no solution => []

2. Ideas
DFS T: O(n) S: O(n)

3. code
3.1) iterable
 1 class Solution:
 2     def pathSum2(self, root, target):
 3         if not root: return []
 4         stack = [(root, [root.val])]
 5         while stack:
 6             node, path = stack.pop()
 7             if node:
 8                 if not node.left and not node.right and sum(path) = target:
 9     
10                     ans.append(path)
11                 if node.right:
12                     stack.append((node.right, path + [node.right.val]))
13                 if node.left:
14                     stack.append((node.left, path + [node.left.val]))
15         return ans

 

3.2) recursive

 1 class Solution:
 2     def pathSum2(self, root, target):
 3         def helper(root, target, path, ans):
 4             if not root.left and not root.right and target ==0:
 5                 ans.append(path)
 6             if root.left:
 7                 helper(root.left, target - root.left.val, path + [root.left.val], ans)
 8             if root.right:
 9                 helper(root.right, target - root.right.val, path + [root.right.val], ans)
10         ans = []
11         if not root: return ans
12         helper(root, target-root.val, [root.val], ans)
13         return ans

 

3.3) path, pathsum append into stack

class Solution:
    def pathSum2(self,root, target):
        if not root: return []
        stack, ans = [(root, [root.val], root.val)], []
        while stack:
            node, path, pathsum = stack.pop()
            if not node.left and not node.right and pathsum == target:
                ans.append(path)
            if node.left:
                stack.append((node.left, path + [node.left.val], pathsum + node.left.val))
            if node.right:
                stack.append((node.right, path + [node.right.val], pathsum + node.right.val))
        return ans

 

4. Test cases

1) empty

2) 1

3)

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