437. Path Sum III - LeetCode Solution


Tree

Python Code:

# 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: TreeNode, target_sum: int) -> int:
        
        
        def dfs(node: TreeNode, sum: List[int]) -> int:
            if not node:
                return 0
            sum = [s + node.val for s in sum] + [node.val]
            res = sum.count(target_sum)
            res += dfs(node.left, sum) if node.left else 0
            res += dfs(node.right, sum) if node.right else 0
            return res
        return dfs(root, [])
        


Comments

Submit
0 Comments
More Questions

1729D - Friends and the Restaurant
1606C - Banknotes
580C - Kefa and Park
342A - Xenia and Divisors
1033A - King Escape
39D - Cubical Planet
1453A - Cancel the Trains
645A - Amity Assessment
1144A - Diverse Strings
1553B - Reverse String
1073A - Diverse Substring
630N - Forecast
312B - Archer
34D - Road Map
630I - Parking Lot
160B - Unlucky Ticket
371B - Fox Dividing Cheese
584B - Kolya and Tanya
137B - Permutation
550C - Divisibility by Eight
5A - Chat Servers Outgoing Traffic
615A - Bulbs
5B - Center Alignment
549A - Face Detection
535B - Tavas and SaDDas
722C - Destroying Array
366A - Dima and Guards
716B - Complete the Word
1461C - Random Events
1627A - Not Shading