From a8a497bc3b1557b97d8e42c89bcecaf89306941b Mon Sep 17 00:00:00 2001 From: Dmitriy Buzulutskiy Date: Tue, 26 Jul 2022 12:19:10 +0600 Subject: [PATCH] Create 235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift --- ...st-Common-Ancestor-of-a-Binary-Search-Tree.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 swift/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift diff --git a/swift/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift b/swift/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift new file mode 100644 index 000000000..a21cdbfa2 --- /dev/null +++ b/swift/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift @@ -0,0 +1,13 @@ +class Solution { + func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> TreeNode? { + guard let root = root, let p = p, let q = q else { return nil } + if root.val < p.val && root.val < q.val { + return lowestCommonAncestor(root.right, p, q) + } else if root.val > p.val && root.val > q.val { + return lowestCommonAncestor(root.left, p, q) + } else { + return root + } + return nil + } +}