Skip to content

Commit 5747010

Browse files
committed
feat: Add solution for LeetCode problem 235
1 parent 766b248 commit 5747010

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//
2+
// 235. Lowest Common Ancestor of a Binary Search Tree
3+
// https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/06/12.
7+
//
8+
9+
/**
10+
* Definition for a binary tree node.
11+
* public class TreeNode {
12+
* public var val: Int
13+
* public var left: TreeNode?
14+
* public var right: TreeNode?
15+
* public init(_ val: Int) {
16+
* self.val = val
17+
* self.left = nil
18+
* self.right = nil
19+
* }
20+
* }
21+
*/
22+
23+
class Solution {
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 }
34+
}
35+
}

0 commit comments

Comments
 (0)