NeetCode #393LC-617EasyTrees
← Back to All Problems#393 · #617 · Merge Two Binary Trees(合并二叉树)
📌 Problem Statement & Constraints
You are given two binary trees
root1 and root2. Merge them: where both nodes exist, the merged value is their sum; otherwise the existing node is used. Return the merged tree. Constraints: the number of nodes in each tree is in [0, 2000], -10^4 <= Node.val <= 10^4.💡 Core Algorithmic Approaches
- Recurse on the two trees in parallel.
- If one side is
None, return the other side directly -- no further work is needed there. - Otherwise add the values and recurse on both children, reusing
root1as the merged node. - This is O(min(n, m)) in the best case and O(n + m) in the worst.
💻 Benchmark Python3 Implementation
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not root1:
return root2 # nothing to merge on this side
if not root2:
return root1
root1.val += root2.val # reuse root1 as the merged node
root1.left = self.mergeTrees(root1.left, root2.left)
root1.right = self.mergeTrees(root1.right, root2.right)
return root1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(min(n, m)) for the overlapping part plus O(1) for the shared subtrees.
💾 Space Complexity
O(h) for the recursion stack.
⚠️ Interview Pitfalls & Follow-ups
- Mutating
root2instead: either is acceptable, but mutating one input should be a deliberate choice. Hereroot1is reused. - Forgetting the
Noneshort-circuits: without them, the recursion would fail onNone.val. - Creating new nodes for the shared subtrees: unnecessary work; the existing subtrees can be attached directly.
- Assuming the trees have the same shape: they generally do not, which the short-circuits handle.