Recursion solution -- good for this problem?


  • 0
    D

    Is a helper function a good practice?

    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """            
    #recursion solution
            #recursive function will return sum of l1 and l2
        
            def addTwoNumbersHelper(l1, l2, carryover):
                if l1 is None and l2 is None and carryover == 0:
                    return None
                
                sum_value = carryover
                carryover = 0
                
                if l1:
                    sum_value += l1.val
                    l1 = l1.next
                if l2:
                    sum_value += l2.val
                    l2 = l2.next
                if sum_value >= 10:
                    carryover = 1
                    sum_value -= 10
                
                return_node = ListNode(sum_value)
                return_node.next = addTwoNumbersHelper(l1, l2, carryover)
                
                return return_node
                    
            return addTwoNumbersHelper(l1,l2,0)
    

Log in to reply
 

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