Leetcode problem #112 - Path Sum
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
Here is my approach in English - I traverse the tree using DFS. When I reach the leaf node in my first else statement, I append the sum of path value to a list. Lastly, I check if my_list
has the targetSum
contained in it. If yes, then return True
else return False
.
# 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: Optional[TreeNode], targetSum: int) -> bool:
my_list = []
def build_some(root, cur_sum):
if not root or targetSum == 0:
return False
elif root.left or root.right:
cur_sum += root.val
build_some(root.left, cur_sum)
build_some(root.right, cur_sum)
else:
my_list.append(cur_sum+root.val)
if targetSum in my_list:
return True
else:
return False
build_some(root, 0)
I am facing a problem with the following testcase:
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
Here, targetSum is 22. The path [5,4,11,2] sums up to 22 and my code works fine in identifying this (which I verified using print(my_list)
). Still, my program is returning False when it should return True. Where am I going wrong in this?
I tried using try
and except
in first else statement to stop the recursive calls if the solution is found but that did not work either.
The hasPathSum
function is missing a return statement so it always returns None
, which evaluates to False
. The last line should be changed to be return build_some(root, 0)
.
(Python functions defined with def do not automatically return the value of the last expression the way that lambdas do.)