Skip to content

Commit 56ca1da

Browse files
author
Joseph Luce
authored
Create 617_merge_two_binary_trees.md
1 parent 4f0fe1f commit 56ca1da

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# 617. Merge Two Binary Trees
2+
3+
## Recursion Solution
4+
5+
- Runtime: O(N)
6+
- Space: O(1) (Assuming creating the result is not extra space)
7+
- N = Number of elements in both trees
8+
9+
By traversing both trees together, the solution is much simpler.
10+
Use one of the trees as your primary merge tree during the recursion and create new nodes when the primary doesn't have one and the secondary tree does.
11+
With recursion, you need to create the new nodes when you are the parent before you perform a function call into that node.
12+
You cannot create the new node if the node doesn't exist after the call.
13+
14+
```
15+
class Solution:
16+
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
17+
def merge_tree_helper(T1, T2):
18+
if T1 is None or T2 is None:
19+
return
20+
T1.val += T2.val #T1 is the primary tree
21+
if T2.left is not None and T1.left is None:
22+
T1.left = TreeNode(0)
23+
if T2.right is not None and T1.right is None:
24+
T1.right = TreeNode(0)
25+
merge_tree_helper(T1.left, T2.left)
26+
merge_tree_helper(T1.right, T2.right)
27+
28+
if t1 is None:
29+
return t2
30+
merge_tree_helper(t1, t2)
31+
return t1
32+
```

0 commit comments

Comments
 (0)