Python: longer may not be worse if (hopefully) more readable


  • 0
    A
    def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if not root:
                return 0
            else:
                if not root.left and not root.right:
                    return 0
                else:
                    result = 0
                    if root.left:
                        result += self.traverse(root.left, True)
                    if root.right:
                        result += self.traverse(root.right, False)
                    return result
        
        def traverse(self, root, isLeft):
            if not root.left and not root.right:
                if isLeft:
                    return root.val
                else:
                    return 0
            else:
                result = 0
                if root.left:
                    result += self.traverse(root.left, True)
                if root.right:
                    result += self.traverse(root.right, False)
                return result
    

Log in to reply
 

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