Skip to main content

Path Sum

Question

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Example 1
Input: 
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

Output:
True (sum of 10 + -3 + 5 = 12)

Solution

all//Path Sum.py


# 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 hasPathSum(self, root, sum):
if root == None:
return False
if root.left == None and root.right == None and root.val == sum:
return True
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)