Skip to content

Commit 8301c33

Browse files
committed
refactor: Optimize lowestCommonAncestor algorithm for BST
- Simplified the logic by leveraging BST properties.
1 parent b24e110 commit 8301c33

File tree

1 file changed

+7
-9
lines changed

1 file changed

+7
-9
lines changed

lowest-common-ancestor-of-a-binary-search-tree/WhiteHyun.swift

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,12 @@
2222

2323
class Solution {
2424
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
3432
}
3533
}

0 commit comments

Comments
 (0)