Skip to content

Commit a4db329

Browse files
committed
Add solution for Merge Two Binary Trees
Signed-off-by: Desgard_Duan <gua@desgard.com>
1 parent 996fa3f commit a4db329

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@
154154
[Path Sum III](https://leetcode.com/problems/path-sum-iiI/)| [Swift](./Tree/PathSumIII.swift)| Easy| O(n^2)| O(1)|
155155
[Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/)| [Swift](./Tree/UniqueBinarySearchTrees.swift)| Medium| O(n^2)| O(n)|
156156
[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)| [Swift](./Tree/RecoverBinarySearchTree.swift)| Hard| O(n)| O(1)|
157+
[Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/) | [Swift](./Tree/MergeTwoBinaryTrees.swift) | Easy | O(n) | O(n) |
157158

158159
## Dynamic programming
159160
| Title | Solution | Difficulty | Time | Space |
@@ -188,6 +189,7 @@
188189
[Burst Ballons](https://leetcode.com/problems/burst-balloons/)| [Swift](./DP/BurstBalloons.swift)| Hard| O(n^3)| O(n)|
189190
[Frog Jump](https://leetcode.com/problems/frog-jump/)| [Swift](./DP/FrogJump.swift)| Hard| O(n^2)| O(n)|
190191

192+
191193
## Depth-first search
192194
| Title | Solution | Difficulty | Time | Space |
193195
| ----- | -------- | ---------- | ---- | ----- |
@@ -767,3 +769,5 @@
767769
| [Swift](./String/LongestSubstringWithoutRepeatingCharacters.swift) | 3 | [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | Medium |
768770
| [Swift](./Math/AddTwoNumbers.swift) | 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | Medium |
769771
| [Swift](./Array/TwoSum.swift) | 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | Easy |
772+
773+

Tree/MergeTwoBinaryTrees.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public var val: Int
5+
* public var left: TreeNode?
6+
* public var right: TreeNode?
7+
* public init(_ val: Int) {
8+
* self.val = val
9+
* self.left = nil
10+
* self.right = nil
11+
* }
12+
* }
13+
*/
14+
class Solution {
15+
func mergeTrees(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? {
16+
guard let t1 = t1 else {
17+
return t2
18+
}
19+
guard let t2 = t2 else {
20+
return t1
21+
}
22+
t1.val += t2.val
23+
t1.left = mergeTrees(t1.left, t2.left)
24+
t1.right = mergeTrees(t1.right, t2.right)
25+
return t1
26+
}
27+
}

0 commit comments

Comments
 (0)