Leetcode 113: Path Sum II

https://leetcode.com/problems/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]
]

 

Code

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        if root is None: return []
        self.res = []
        self._pathSum(root, sum, [])
        return self.res
        
    def _pathSum(self, root, sum, l):
        l += [root.val]
        if root.left is None and root.right is None: 
            if sum==root.val:
                self.res += [l[:]]
        
        if root.left: self._pathSum(root.left, sum-root.val, l) 
        if root.right: self._pathSum(root.right, sum-root.val, l) 
        l.pop()
        
        
        

 

Idea

Use DSP to traverse every node in the tree. Pass the path from the root to the current node as a parameter in the traversal. Whenever it reaches a leaf, count if all nodes in the path sum to the target number. When a node finishes traversing its left node and right node, it should be popped out of the path.

Line 24: when you add current path (`l`) into `self.res`, you need to make a deep copy of `l`: `l[:]`

Leave a comment

Your email address will not be published. Required fields are marked *