-1

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.

MLENGG
  • 1
  • To solve problems like you have, you have to learn how to [debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your code. Start by creating a [mre], with the input hard-coded, that you can run, test and debug locally on your own system. Then use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) together with pen and paper to step through the code line by line, while monitoring variables and their values, to try and figure out what happens and when and where things start to go wrong. – Some programmer dude Aug 23 '23 at 03:18
  • Though in this case, some quick [rubber duck debugging](https://en.wikipedia.org/wiki/Rubber_duck_debugging) should have helped you figure out one serious flaw in the `DFS` function... Does all paths through that function actually return a value? Remember: If you want to return a value from a function, you must use an explicit `return` statement. Also, if you don't have a `return` statement then execution will continue in the function. – Some programmer dude Aug 23 '23 at 03:20

0 Answers0