Skip to content

Commit f87fc4b

Browse files
authored
feat: add swift implementation to lcof problem: No.68.2 (#2964)
1 parent b9a4792 commit f87fc4b

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

lcof/面试题68 - II. 二叉树的最近公共祖先/README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,41 @@ var lowestCommonAncestor = function (root, p, q) {
295295
};
296296
```
297297

298+
#### Swift
299+
300+
```swift
301+
/* public class TreeNode {
302+
* public var val: Int
303+
* public var left: TreeNode?
304+
* public var right: TreeNode?
305+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
306+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
307+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
308+
* self.val = val
309+
* self.left = left
310+
* self.right = right
311+
* }
312+
* }
313+
*/
314+
315+
class Solution {
316+
func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode, _ q: TreeNode) -> TreeNode? {
317+
if root == nil || root === p || root === q {
318+
return root
319+
}
320+
321+
let left = lowestCommonAncestor(root?.left, p, q)
322+
let right = lowestCommonAncestor(root?.right, p, q)
323+
324+
if let _ = left, let _ = right {
325+
return root
326+
}
327+
328+
return left ?? right
329+
}
330+
}
331+
```
332+
298333
<!-- tabs:end -->
299334

300335
<!-- solution:end -->
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/* public class TreeNode {
2+
* public var val: Int
3+
* public var left: TreeNode?
4+
* public var right: TreeNode?
5+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
6+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
7+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
8+
* self.val = val
9+
* self.left = left
10+
* self.right = right
11+
* }
12+
* }
13+
*/
14+
15+
class Solution {
16+
func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode, _ q: TreeNode) -> TreeNode? {
17+
if root == nil || root === p || root === q {
18+
return root
19+
}
20+
21+
let left = lowestCommonAncestor(root?.left, p, q)
22+
let right = lowestCommonAncestor(root?.right, p, q)
23+
24+
if let _ = left, let _ = right {
25+
return root
26+
}
27+
28+
return left ?? right
29+
}
30+
}

0 commit comments

Comments
 (0)