Skip to content

Commit c344520

Browse files
author
Joseph Luce
authored
Update 617_merge_two_binary_trees.md
1 parent 56ca1da commit c344520

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

leetcode/easy/617_merge_two_binary_trees.md

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
# 617. Merge Two Binary Trees
22

3-
## Recursion Solution
3+
## Recursive Solution
44

55
- Runtime: O(N)
6-
- Space: O(1) (Assuming creating the result is not extra space)
6+
- Space: O(N)
77
- N = Number of elements in both trees
88

99
By traversing both trees together, the solution is much simpler.
1010
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.
1111
With recursion, you need to create the new nodes when you are the parent before you perform a function call into that node.
1212
You cannot create the new node if the node doesn't exist after the call.
1313

14+
Recursion always has O(N) at the very least.
15+
1416
```
1517
class Solution:
1618
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
@@ -30,3 +32,32 @@ class Solution:
3032
merge_tree_helper(t1, t2)
3133
return t1
3234
```
35+
36+
## Iterative Solution
37+
38+
- Runtime: O(N)
39+
- Space: O(N)
40+
- N = Number of elements in both trees
41+
42+
Similar to the recursion solution, however, will need to keep two items in the each element of the stack since the idea was to traverse the nodes in pairs. You could use two stacks but I believe the code would be more clunky.
43+
44+
```
45+
class Solution:
46+
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
47+
if t1 is None:
48+
return t2
49+
stack = list()
50+
stack.append((t1, t2))
51+
while len(stack) > 0:
52+
node1, node2 = stack.pop()
53+
if node1 is None or node2 is None:
54+
continue
55+
node1.val += node2.val
56+
if node2.left is not None and node1.left is None:
57+
node1.left = TreeNode(0)
58+
if node2.right is not None and node1.right is None:
59+
node1.right = TreeNode(0)
60+
stack.append((node1.left, node2.left))
61+
stack.append((node1.right, node2.right))
62+
return t1
63+
```

0 commit comments

Comments
 (0)