Skip to content

Latest commit

 

History

History
50 lines (40 loc) · 1.24 KB

113.Path-Sum-II.md

File metadata and controls

50 lines (40 loc) · 1.24 KB

113. Path Sum II

Difficulty: Medium

URL

https://leetcode.com/problems/path-sum-ii/

Solution

Approach 1: Backtracking

The code is shown below:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        path = []
        res = []
        if not root:
            return res
        
        def backtracking(node, cur_sum):
            nonlocal path, res
            if not node.left and not node.right:
                if cur_sum != targetSum:
                    return
                else:
                    res.append(path[:])
                    return
            
            if node.left:
                path.append(node.left.val)
                backtracking(node.left, cur_sum + node.left.val)
                path.pop()
            if node.right:
                path.append(node.right.val)
                backtracking(node.right, cur_sum + node.right.val)
                path.pop()
        
        path.append(root.val)
        backtracking(root, root.val)
        return res