File tree Expand file tree Collapse file tree 1 file changed +7
-9
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +7
-9
lines changed Original file line number Diff line number Diff line change 22
22
23
23
class Solution {
24
24
func lowestCommonAncestor( _ root: TreeNode ? , _ p: TreeNode ? , _ q: TreeNode ? ) -> TreeNode ? {
25
- if root == nil { return nil }
26
- if root == p { return p }
27
- if root == q { return q }
28
- let left = lowestCommonAncestor ( root? . left, p, q)
29
- let right = lowestCommonAncestor ( root? . right, p, q)
30
-
31
- if left != nil , right != nil { return root }
32
- else if left != nil { return left }
33
- else { return right }
25
+ guard let root else { return nil }
26
+ if root. val < p!. val, root. val < q!. val {
27
+ return lowestCommonAncestor ( root. right, p, q)
28
+ } else if root. val > p!. val, root. val > q!. val {
29
+ return lowestCommonAncestor ( root. left, p, q)
30
+ }
31
+ return root
34
32
}
35
33
}
You can’t perform that action at this time.
0 commit comments