Skip to content

Commit fd7b751

Browse files
committed
Swift implementation for LCOF 68-I
1 parent 32c0fd2 commit fd7b751

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,40 @@ var lowestCommonAncestor = function (root, p, q) {
270270
};
271271
```
272272

273+
#### Swift
274+
275+
```swift
276+
/* public class TreeNode {
277+
* public var val: Int
278+
* public var left: TreeNode?
279+
* public var right: TreeNode?
280+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
281+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
282+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
283+
* self.val = val
284+
* self.left = left
285+
* self.right = right
286+
* }
287+
* }
288+
*/
289+
290+
class Solution {
291+
func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode, _ q: TreeNode) -> TreeNode? {
292+
var node = root
293+
while let current = node {
294+
if current.val < p.val && current.val < q.val {
295+
node = current.right
296+
} else if current.val > p.val && current.val > q.val {
297+
node = current.left
298+
} else {
299+
return current
300+
}
301+
}
302+
return nil
303+
}
304+
}
305+
```
306+
273307
<!-- tabs:end -->
274308

275309
<!-- solution:end -->
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
var node = root
18+
while let current = node {
19+
if current.val < p.val && current.val < q.val {
20+
node = current.right
21+
} else if current.val > p.val && current.val > q.val {
22+
node = current.left
23+
} else {
24+
return current
25+
}
26+
}
27+
return nil
28+
}
29+
}

0 commit comments

Comments
 (0)