Problem statement

https://binarysearch.com/problems/Merging-Binary-Trees/

Solution

Equal to Leetcode 0617 Merge Two Binary Trees

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 solve(self, t1, t2):
        if t1 and t2:
            t1.val += t2.val
            t1.left = self.solve(t1.left, t2.left)
            t1.right = self.solve(t1.right, t2.right)
            return t1
        
        if t1 and not t2: return t1
        if t2 and not t1: return t2