Simple Python recursive

  • 3

    The idea is simple, when t1 and t2 are both None, return None otherwise just turtle all the way down.

    class Solution(object):
        def mergeTrees(self, t1, t2):
            :type t1: TreeNode
            :type t2: TreeNode
            :rtype: TreeNode
            if not t1 and not t2: return None
            if t1:
                v1, L1, R1 = t1.val, t1.left, t1.right
                v1, L1, R1 = 0, None, None
            if t2:
                v2, L2, R2 = t2.val, t2.left, t2.right
                v2, L2, R2 = 0, None, None
            node = TreeNode(v1+v2)
            node.left = self.mergeTrees(L1, L2)
            node.right = self.mergeTrees(R1, R2)
            return node

Log in to reply

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