use dfs with python


  • 1
    E
    class Solution(object):
        def hasPathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: bool
            """
            # root is [] return 0
            if root is None:
                return False
                    
            return self.dfsPath(root, sum)
        
        def dfsPath(self, node, sum):
            if node is not None:
                sum -= node.val
                if node.left is None and node.right is None and sum is 0:
                    return True
                elif node.left is None and node.right is None:
                    return False
                else:
                    return self.dfsPath(node.left, sum) or self.dfsPath(node.right, sum)
            return False
    

Log in to reply
 

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