Python clean code


  • 0
    K

    class Solution(object):
    def init(self):
    self.target = 0

    def isLeaf(self, node):
        if node.left or node.right:
            return False
        else:
            return True
        
    def cal(self, node, prevSum):
        if not node:
            return False
        if self.isLeaf(node):
            return prevSum + node.val == self.target
        else:
            return self.cal(node.left, prevSum + node.val) or self.cal(node.right, prevSum + node.val)
            
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        self.target = sum
        return self.cal(root, 0)

  • 0
    K

    @kakahu
    Sorry, bad format above.

    class Solution(object):
    def __init__(self):
        self.target = 0
        
    def isLeaf(self, node):
        if node.left or node.right:
            return False
        else:
            return True
        
    def cal(self, node, prevSum):
        if not node:
            return False
        if self.isLeaf(node):
            return prevSum + node.val == self.target
        else:
            return self.cal(node.left, prevSum + node.val) or self.cal(node.right, prevSum + node.val)
            
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        self.target = sum
        return self.cal(root, 0)

Log in to reply
 

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