Skip to content

Commit c8017a5

Browse files
authored
Merge pull request #2319 from socow/main
[socow] WEEK 13 solutions
2 parents f824e4d + 5f668ea commit c8017a5

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

  • lowest-common-ancestor-of-a-binary-search-tree
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/
4+
5+
Solution:
6+
BST의 특성을 활용한다.
7+
1) p, q 모두 현재 노드보다 작으면 → LCA는 왼쪽 서브트리에 존재
8+
2) p, q 모두 현재 노드보다 크면 → LCA는 오른쪽 서브트리에 존재
9+
3) 그 외의 경우 → 현재 노드가 LCA (p, q가 갈라지는 지점)
10+
11+
Time: O(log n) - 균형 BST 기준, 최악의 경우 O(n)
12+
Space: O(1)
13+
"""
14+
15+
16+
# Definition for a binary tree node.
17+
class TreeNode:
18+
def __init__(self, x):
19+
self.val = x
20+
self.left = None
21+
self.right = None
22+
23+
24+
class Solution:
25+
def lowestCommonAncestor(
26+
self, root: "TreeNode", p: "TreeNode", q: "TreeNode"
27+
) -> "TreeNode":
28+
cur = root
29+
while cur:
30+
if p.val < cur.val and q.val < cur.val:
31+
cur = cur.left
32+
elif p.val > cur.val and q.val > cur.val:
33+
cur = cur.right
34+
else:
35+
return cur

0 commit comments

Comments
 (0)