Python BFS Solution


  • 1
    J
    class Solution(object):
        def mergeTrees(self, t1, t2):
            """
            :type t1: TreeNode
            :type t2: TreeNode
            :rtype: TreeNode
            """
            if not (t1 and t2):
                return t1 or t2
            queue1, queue2 = collections.deque([t1]), collections.deque([t2])
            while queue1 and queue2:
                node1, node2 = queue1.popleft(), queue2.popleft()
                if node1 and node2:
                    node1.val = node1.val + node2.val
                    if (not node1.left) and node2.left:
                        node1.left = TreeNode(0)
                    if (not node1.right) and node2.right:
                        node1.right = TreeNode(0)
                    queue1.append(node1.left)
                    queue1.append(node1.right)
                    queue2.append(node2.left)
                    queue2.append(node2.right)
            return t1
    

Log in to reply
 

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