You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: leetcode/easy/617_merge_two_binary_trees.md
+33-2Lines changed: 33 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,16 +1,18 @@
1
1
# 617. Merge Two Binary Trees
2
2
3
-
## Recursion Solution
3
+
## Recursive Solution
4
4
5
5
- Runtime: O(N)
6
-
- Space: O(1) (Assuming creating the result is not extra space)
6
+
- Space: O(N)
7
7
- N = Number of elements in both trees
8
8
9
9
By traversing both trees together, the solution is much simpler.
10
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
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
12
You cannot create the new node if the node doesn't exist after the call.
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.
0 commit comments