Skip to content

Commit eb91f79

Browse files
committed
lowest-common-ancestor-of-a-binary-search-tree solution (py)
1 parent 97cade6 commit eb91f79

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# μ£Όμ–΄μ§„ BST와 λ…Έλ“œ p, qκ°€ μ£Όμ–΄μ§ˆ λ•Œ
2+
# 이 λ‘˜μ˜ κ°€μž₯ κ°€κΉŒμš΄ 곡톡 쑰상(Lowest Common Ancestor, LCA)을 μ°Ύμ•„ λ°˜ν™˜ν•΄λΌ
3+
# 곡톡 μ‘°μƒμ΄λž€, p와 q λͺ¨λ‘μ˜ 쑰상 μ€‘μ—μ„œ κ°€μž₯ κΉŠμ€ λ…Έλ“œλ₯Ό 의미
4+
#
5+
# BST(Binary Search Tree)의 νŠΉμ§•
6+
# - 각 λ…Έλ“œλŠ” μ΅œλŒ€ 두 개의 μžμ‹ λ…Έλ“œλ₯Ό κ°€μ§ˆ 수 있음
7+
# - μ™Όμͺ½ μ„œλΈŒνŠΈλ¦¬μ˜ λͺ¨λ“  값은 ν˜„μž¬ λ…Έλ“œλ³΄λ‹€ μž‘κ³ ,
8+
# - 였λ₯Έμͺ½ μ„œλΈŒνŠΈλ¦¬μ˜ λͺ¨λ“  값은 ν˜„μž¬ λ…Έλ“œλ³΄λ‹€ 큼.
9+
#
10+
# 풀이
11+
# ν˜„μž¬ λ…Έλ“œκ°€ p, q보닀 λ‘˜ λ‹€ μž‘μœΌλ©΄, 였λ₯Έμͺ½ μ„œλΈŒνŠΈλ¦¬μ—μ„œ LCAλ₯Ό μ°Ύκ³ ,
12+
# λ‘˜ λ‹€ 크면, μ™Όμͺ½ μ„œλΈŒ νŠΈλ¦¬μ—μ„œ μ°Ύκ³ ,
13+
# ν•œμͺ½μ€ μž‘κ³ , ν•œμͺ½μ€ 크면 ν˜„μž¬ λ…Έλ“œκ°€ LCAκ°€ 됨.
14+
15+
# TC: O(H), HλŠ” 이진 검색 트리의 높이
16+
# SC: O(H), μž¬κ·€ μŠ€νƒμ— ν•„μš”ν•œ 곡간
17+
18+
# Definition for a binary tree node.
19+
class TreeNode:
20+
def __init__(self, x):
21+
self.val = x
22+
self.left = None
23+
self.right = None
24+
25+
# μž¬κ·€ 풀이
26+
# TC: O(H), HλŠ” 이진 검색 트리의 높이
27+
# SC: O(H), μž¬κ·€ μŠ€νƒμ— ν•„μš”ν•œ 곡간
28+
class Solution:
29+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
30+
if p.val < root.val and q.val < root.val:
31+
return self.lowestCommonAncestor(root.left, p, q)
32+
if root.val < p.val and root.val < q.val:
33+
return self.lowestCommonAncestor(root.right, p, q)
34+
return root
35+
36+
# 반볡 풀이
37+
# TC: O(H), HλŠ” 이진 검색 트리의 높이
38+
# SC: O(1)
39+
class Solution:
40+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
41+
node = root
42+
while node:
43+
if p.val < node.val and q.val < node.val:
44+
node = node.left
45+
elif node.val < p.val and node.val < q.val:
46+
node = node.right
47+
else:
48+
return node

0 commit comments

Comments
Β (0)