Problem statement

https://leetcode.com/problems/merge-two-binary-trees/

Solution

One possible solution is to use recursion.

Complexity

Time complexity is O(n1 + n2), where n1 and n2 are number of nodes in each tree and space complexity is O(max(h1, h2)), where h1 and h2 are heights of trees.

Code

class Solution:
    def mergeTrees(self, t1, t2):
        if t1 and t2:
            t1.val += t2.val
            t1.left = self.mergeTrees(t1.left, t2.left)
            t1.right = self.mergeTrees(t1.right, t2.right)
            return t1
        
        if t1 and not t2: return t1
        if t2 and not t1: return t2