Python inplace: beats 93%


  • 0
    E

    The simple recursive solution, except we are merging the trees into t1 instead of making a new one.

    def process_nodes(t1, t2): # double inorder traversal
        if t1 and t2:
            t1.val += t2.val
        elif t2 and not t1:
            return t2
        elif t1 and not t2:
            return t1
        elif not t1 and not t2:
            return None
        
        t1.left = process_nodes(t1.left, t2.left)
        t1.right = process_nodes(t1.right, t2.right)
        return t1
        
            
    class Solution:
        def mergeTrees(self, t1, t2):
            """
            :type t1: TreeNode
            :type t2: TreeNode
            :rtype: TreeNode
            """
            
            t1 = process_nodes(t1, t2)
            return t1
    

Log in to reply
 

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