My Python Recursive Solution Well Commented in O(1) Extra Space


  • -1
    S
     def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if root is None:
                return 0
            if root.left is None and root.right is None:#IF THE TREE HAS ONLY ONE NODE
                return 0
            return self.sumup(root)
        def sumup(self,root):    
            if root is None:
                return 0
            if root.left is None and root.right is None:
                return root.val
            sum_left=self.sumup(root.left)
            if root.right!=None and root.right.left is None and root.right.right is None:#JUST AS YOU CALCULATE SUM OF LEAF NODE JUST CHECK IF IT IS A RIGHT LEAF NODE SIMPLY SET SUM_RIGHT TO ZERO ELSE GO IN SIMILAR FASHION
                sum_right=0
            else:    
               sum_right=self.sumup(root.right)# GO IN SIMILAR FASHION
            #print sum_left+sum_right
            return sum_left+sum_right# RETURN THE CALCULATED VALUE FROM LEFT SUBTREE AND RIGHT SUBTREE
            
            
    

Log in to reply
 

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