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 overlap while the others do not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of the new tree.
Return the merged tree.
Note: The merging process must start from the root nodes of both trees.
Example:
Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
Output: [3,4,5,5,4,null,7]
TreeNode
objects?
TreeNode
objects.We will use a recursive approach to solve this problem. The recursive function will handle the following scenarios:
The base cases for the recursion handle scenarios where at least one of the nodes is null.
Here’s the Python code to merge two binary trees:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def mergeTrees(t1: TreeNode, t2: TreeNode) -> TreeNode:
if not t1:
return t2
if not t2:
return t1
merged = TreeNode(t1.val + t2.val)
merged.left = mergeTrees(t1.left, t2.left)
merged.right = mergeTrees(t1.right, t2.right)
return merged
The time complexity of this approach is O(N), where N is the total number of nodes in the smaller tree. This is because we visit each node exactly once.
The space complexity is O(H), where H is the height of the tree. This is due to the recursive call stack. In the worst case (completely unbalanced tree), H can be as large as N. However, in the best case (completely balanced tree), H will be log(N).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?