From 728519d2fc0a9320af946794cff298f62fab240c Mon Sep 17 00:00:00 2001 From: socow Date: Fri, 6 Feb 2026 14:58:51 +0900 Subject: [PATCH 1/2] 235. Lowest Common Ancestor of a Binary Search Tree --- .../socow.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 lowest-common-ancestor-of-a-binary-search-tree/socow.py diff --git a/lowest-common-ancestor-of-a-binary-search-tree/socow.py b/lowest-common-ancestor-of-a-binary-search-tree/socow.py new file mode 100644 index 0000000000..90ffc03447 --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree/socow.py @@ -0,0 +1,35 @@ +""" +235. Lowest Common Ancestor of a Binary Search Tree +https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ + +Solution: + BST의 특성을 활용한다. + 1) p, q 모두 현재 노드보다 작으면 → LCA는 왼쪽 서브트리에 존재 + 2) p, q 모두 현재 노드보다 크면 → LCA는 오른쪽 서브트리에 존재 + 3) 그 외의 경우 → 현재 노드가 LCA (p, q가 갈라지는 지점) + +Time: O(log n) - 균형 BST 기준, 최악의 경우 O(n) +Space: O(1) +""" + + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + +class Solution: + def lowestCommonAncestor( + self, root: "TreeNode", p: "TreeNode", q: "TreeNode" + ) -> "TreeNode": + cur = root + while cur: + if p.val < cur.val and q.val < cur.val: + cur = cur.left + elif p.val > cur.val and q.val > cur.val: + cur = cur.right + else: + return cur \ No newline at end of file From 5f668eaea619756ffadf650a44459500e65a1659 Mon Sep 17 00:00:00 2001 From: socow Date: Fri, 6 Feb 2026 15:00:23 +0900 Subject: [PATCH 2/2] 235. Lowest Common Ancestor of a Binary Search Tree --- lowest-common-ancestor-of-a-binary-search-tree/socow.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lowest-common-ancestor-of-a-binary-search-tree/socow.py b/lowest-common-ancestor-of-a-binary-search-tree/socow.py index 90ffc03447..70bfa2632b 100644 --- a/lowest-common-ancestor-of-a-binary-search-tree/socow.py +++ b/lowest-common-ancestor-of-a-binary-search-tree/socow.py @@ -32,4 +32,4 @@ def lowestCommonAncestor( elif p.val > cur.val and q.val > cur.val: cur = cur.right else: - return cur \ No newline at end of file + return cur