functional approach. Solved without using global or class member variable


  • 0
    D
    def sumNumbersUtil(self, root, max_so_far, total):
    
        if (root is None):
            return total
    
        total = self.sumNumbersUtil(root.left, str(root.val) + str(max_so_far), total)
        total = self.sumNumbersUtil(root.right, str(root.val) + str(max_so_far), total)
        if (root.left is None and root.right is None):
            temp=(str(root.val) + max_so_far)[::-1]
            total += int(temp)
        return total
    
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if (root is None):
            return 0
    
        total = 0
        max_so_far=""
        return self.sumNumbersUtil(root, max_so_far, total)

Log in to reply
 

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