Could anyone tell me what is wrong with my code?


  • 0
    Q
    class Solution:
    # @param root, a tree node
    # @param sum, an integer
    # @return a boolean
    def hasPathSum(self, root, sum):
    
        node = root
        
        if node.left==None and node.right==None and sum==node.val:
            return True
        
        if node.left != None:
            node = node.left
            hasPathSum(self, node, sum-node.val)
            
        if node.right != None:
            node = node.right
            hasPathSum(self, node, sum-node.val)
        
        return False
    

    Here is the error message:
    Runtime Error Message: Line 16: AttributeError: 'NoneType' object has no attribute 'left'
    Last executed input: {}, 1

    I just want to know how to fix it, thanks!


  • 0
    Y

    If you want use recursive method

    {
    def hasPathSum(self, root, sum):

        node = root
        
        if not node:
            return False
        
        if node.left==None and node.right==None and sum==node.val:
            return True
        
        if node.left and self.hasPathSum(node.left,sum-node.val):
            return True
        elif node.right and self.hasPathSum(node.right,sum-node.val):
            return True
        else:
            return False
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.