My solution in Python


  • 0
    G

    I think it is very good.

    # Definition for a  binary tree node
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        # @param root, a tree node
        # @param sum, an integer
        # @return a boolean
        def hasPathSum(self, root, sum):
            if root==None:
                return False
            if root.left==None and root.right==None and root.val==sum:
                return True
            if root.left!=None:
                if self.hasPathSum(root.left,sum-root.val)==True:
                    return True
            if root.right!=None:
                if self.hasPathSum(root.right,sum-root.val)==True:
                    return True
            return False

  • 5
    K

    you can maybe save some steps:

    def hasPathSum(self, root, sum):
        if root:
            return not root.left and not root.right and sum==root.val or self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)
        return False

Log in to reply
 

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