Skip to content

Commit b9a4792

Browse files
authored
feat: add swift implementation to lcof problem: No.68.1 (#2963)
1 parent ae32a3d commit b9a4792

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,44 @@ function lowestCommonAncestor(
416416
}
417417
```
418418

419+
#### Swift
420+
421+
```swift
422+
/**
423+
* Definition for a binary tree node.
424+
* public class TreeNode {
425+
* public var val: Int
426+
* public var left: TreeNode?
427+
* public var right: TreeNode?
428+
* public init(_ val: Int) {
429+
* self.val = val
430+
* self.left = nil
431+
* self.right = nil
432+
* }
433+
* }
434+
*/
435+
436+
class Solution {
437+
func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> TreeNode? {
438+
guard let p = p, let q = q else {
439+
return nil
440+
}
441+
442+
var node = root
443+
while let current = node {
444+
if current.val < p.val && current.val < q.val {
445+
node = current.right
446+
} else if current.val > p.val && current.val > q.val {
447+
node = current.left
448+
} else {
449+
return current
450+
}
451+
}
452+
return nil
453+
}
454+
}
455+
```
456+
419457
<!-- tabs:end -->
420458

421459
<!-- solution:end -->
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
15+
class Solution {
16+
func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> TreeNode? {
17+
guard let p = p, let q = q else {
18+
return nil
19+
}
20+
21+
var node = root
22+
while let current = node {
23+
if current.val < p.val && current.val < q.val {
24+
node = current.right
25+
} else if current.val > p.val && current.val > q.val {
26+
node = current.left
27+
} else {
28+
return current
29+
}
30+
}
31+
return nil
32+
}
33+
}

0 commit comments

Comments
 (0)