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
Difficulty
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
AI Disclaimer
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.
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 returnsNone, correctly representing an empty merged tree. - One root is
Nonewhile 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
root1directly 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
Nonecases 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 156: Binary Tree Upside Down
- problem 426: Convert Binary Search Tree to Sorted Doubly Linked List
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 237: Delete Node in a Linked List
- problem 260: Single Number III
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
Extra
- 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