Python : Why wrong result


  • 0
    S

    The follow code doesn't gives the corrent result
    '''
    class Solution(object):
    def convertBST(self, root):
    nums = []
    def func1(r1):
    if r1 != None:
    nums.append(r1.val)
    func1(r1.left)
    func1(r1.right)

        def func2(r2):
            if r2 != None:
                for num in nums:
                    if num > r2.val:
                        r2.val += num
                       
                
                func2(r2.left)
                func2(r2.right)
        
        func1(root)
        func2(root)
        
        return root
    

    '''

    But the following code gives the corrent result (although it is very slow and gets TLE)
    '''
    class Solution(object):
    def convertBST(self, root):
    nums = []
    def func1(r1):
    if r1 != None:
    nums.append(r1.val)
    func1(r1.left)
    func1(r1.right)

        def func2(r2):
            if r2 != None:               
                r2.val += sum([num2 for num2 in nums if num2 > r2.val])
                
                func2(r2.left)
                func2(r2.right)
        
        func1(root)
        func2(root)
        
        return root
    

    '''
    Why the second code works but the first doesn't?


Log in to reply
 

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