Merge Two Binary Trees — LeetCode 617 Python Solution

EasyTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#617
Reading time
3 min

The problem

You are given two binary trees root1 and root2. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

Example

Input
root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
Output
[3,4,5,5,4,null,7]

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def mergeTrees(
        self, root1: Optional[TreeNode], root2: Optional[TreeNode]
    ) -> Optional[TreeNode]:
        if root1 is None:
            return root2
        if root2 is None:
            return root1
        node = TreeNode(root1.val + root2.val)
        node.left = self.mergeTrees(root1.left, root2.left)
        node.right = self.mergeTrees(root1.right, root2.right)
        return node

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 617. Merge Two Binary Trees is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 617. Merge Two Binary Trees?
LeetCode 617. Merge Two Binary Trees is rated Easy on LeetCode.
What is the time complexity of LeetCode 617. Merge Two Binary Trees?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 617. Merge Two Binary Trees?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 617. Merge Two Binary Trees cover?
LeetCode 617. Merge Two Binary Trees is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview