File tree Expand file tree Collapse file tree 2 files changed +71
-0
lines changed
lcof/面试题68 - I. 二叉搜索树的最近公共祖先 Expand file tree Collapse file tree 2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change @@ -416,6 +416,44 @@ function lowestCommonAncestor(
416
416
}
417
417
```
418
418
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
+
419
457
<!-- tabs: end -->
420
458
421
459
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments