I'm doing leetcode where I've to determine if a given targetValue is the sum of values from tree to any leaf (path sum).
tree image a shown here. targetSum is 22, so my function should return True(as one of the path sum equals 22).
I've written this code below while I'm getting the right value when I print it but function is not returning the correct output.
Can someone please explain what's going wrong with this code
class Solution(object):
def hasPathSum(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: bool
"""
def DFS(root,sums):
sums+= root.val
if root.right:
DFS(root.right,sums)
if root.left:
DFS(root.left,sums)
if not root.right and not root.left:
print(sums)
print(sums == targetSum)
return sums == targetSum
if root:
return DFS(root,0)
Stdout
18
False
26
False
22
True
27
False
output : False
I've tried DFS using recursion, I'm able to get the path sums correctly for each path but return value is not correct.