Problem 617

Abstract / Summary

Merge two binary trees by combining their nodes and summing values at overlapping positions.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0617.py

class Solution:
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root1 and not root2:
            return None
        if root1 and not root2:
            return root1
        if root2 and not root1:
            return root2

        root1.val += root2.val
        root1.left  = self.mergeTrees(root1.left,  root2.left)
        root1.right = self.mergeTrees(root1.right, root2.right)
        return root1
13 lines | 485 bytes | submitted September 4, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 79% (1+ million submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Breadth First Search
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method mergeTrees that takes two binary tree roots and returns a new tree representing the element-wise sum of the input trees. The algorithm works recursively, merging corresponding nodes and preserving the structure of both trees. The function returns a reference to the merged tree, reusing nodes from the first tree whenever possible.

Key Steps

The method begins by handling the situation where both input nodes are absent. In that case the function returns None, indicating that there is no subtree to attach.

if not root1 and not root2:
    return None

If only one of the two nodes exists, the function returns the existing node directly. This short-circuit avoids unnecessary recursion and ensures that the remaining subtree is attached unchanged.

if root1 and not root2:
    return root1
if root2 and not root1:
    return root2

When both nodes are present, the algorithm updates the value of the first node by adding the value of the second node. This in-place modification means the merged tree reuses the memory of the first input tree.

root1.val += root2.val

The left and right children are then merged by recursively invoking mergeTrees on the corresponding child pairs. The results are assigned back to the left and right pointers of the first node, preserving the merged structure.

root1.left  = self.mergeTrees(root1.left,  root2.left)
root1.right = self.mergeTrees(root1.right, root2.right)

Finally, the method returns the modified first node, which now serves as the root of the merged subtree.

return root1

Edge Cases

The code explicitly addresses three edge conditions:

  • Both input roots are None. The function returns None, correctly representing an empty merged tree.
  • One root is None while the other is not. The non-null root is returned unchanged, ensuring that any existing subtree is preserved without alteration.
  • Nodes exist at different depths in the two trees. Because the recursion proceeds only when both nodes are present, any missing branch in one tree is automatically filled by the corresponding branch from the other tree, thanks to the early return for single-node cases.

These checks guarantee that the algorithm behaves correctly for trees of unequal shape, for completely empty inputs, and for partially overlapping structures.

Performance Optimizations

The implementation achieves efficiency through several implicit optimizations:

  • In-place updates: By modifying root1 directly and returning it, the algorithm avoids allocating new node objects for the merged tree. This reduces memory overhead and the cost of object construction.
  • Early termination: The conditional returns for None cases prevent unnecessary recursive calls when one subtree is absent, cutting down the number of function invocations.
  • Tail recursion pattern: Each recursive call returns a node that is immediately assigned to a child pointer, allowing the interpreter to reuse stack frames efficiently during the depth-first traversal.

Collectively, these choices lead to a solution that merges the trees with minimal additional memory usage and a reduced number of recursive steps compared to a naïve approach that would always create new nodes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine two different trees made out of building blocks. Each block has a special number written on it. This code is like a magical game that mashes two trees together into one brand new, super tree.

First, the code looks at both spots where a tree might be. If there is nothing in either spot, it knows there is nothing to do. If one tree has blocks and the other is empty, the code just picks up the tree that has blocks and keeps it.

When both trees have blocks in the same spot, the code takes the number on the first block and adds the number from the second block to it. Now that block has a bigger, combined value. Then, the code plays this same game on the left side of the tree and the right side of the tree to make sure every single piece gets joined together properly. By doing this over and over for all the branches, all the little trees become one big, happy tree.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.92 | σ = 0.83

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust JS Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
FelixFan1122 C#
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
MacJim C++
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
FelixFan1122 C#
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
MacJim C++
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
zfang399 C++
40 links | 25 authors | 10 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

3 easy 21 medium
25 solutions   September 4, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality