File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments