Skip to content

Commit f9b004f

Browse files
committed
solve: Lowest common ancestor of a BST
1 parent 528d4c7 commit f9b004f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
Constraints:
3+
- The number of nodes in the tree is in the range [2, 10^5].
4+
- -10^9 <= Node.val <= 10^9
5+
- All Node.val are unique.
6+
- p != q
7+
- p and q will exist in the BST.
8+
9+
Time Complexity: O(h)
10+
- ์—ฌ๊ธฐ์„œ h๋Š” ํŠธ๋ฆฌ์˜ ๋†’์ด
11+
12+
Space Complexity: O(1)
13+
- node ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ ์ƒ์ˆ˜๊ณต๊ฐ„
14+
15+
ํ’€์ด๋ฐฉ๋ฒ•:
16+
1. LCA ๋…ธ๋“œ๋ž€:
17+
- ๋‘ ๋…ธ๋“œ ์ค‘ ํ•˜๋‚˜๊ฐ€ ๋‹ค๋ฅธ ํ•˜๋‚˜์˜ ์กฐ์ƒ์ธ ๊ฒฝ์šฐ, ์ƒ์œ„์— ์œ„์น˜ํ•œ ๋…ธ๋“œ๊ฐ€ LDA
18+
- ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด, ๋‘ ๋…ธ๋“œ๋ฅผ ํƒ€๊ณ  ์œ„๋กœ ์˜ฌ๋ผ๊ฐ€๋ฉด ์ฒ˜์Œ ๋งŒ๋‚˜๋Š” ๋…ธ๋“œ๊ฐ€ LDA
19+
2. BST์—์„œ LCA ์ฐพ๊ธฐ:
20+
- ํ˜„์žฌ ๋…ธ๋“œ์˜ ๊ฐ’์ด p์™€ q๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ -> ์™ผ์ชฝ์œผ๋กœ ์ด๋™
21+
- ํ˜„์žฌ ๋…ธ๋“œ์˜ ๊ฐ’์ด p์™€ q๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ -> ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ด๋™
22+
- ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ(ํ˜„์žฌ ๋…ธ๋“œ๊ฐ€ p์™€ q ์‚ฌ์ด์— ์žˆ๊ฑฐ๋‚˜ p๋‚˜ q ์ค‘ ํ•˜๋‚˜์™€ ๊ฐ™์œผ๋ฉด) -> ํ˜„์žฌ ๋…ธ๋“œ๊ฐ€ LCA
23+
"""
24+
# Definition for a binary tree node.
25+
# class TreeNode:
26+
# def __init__(self, x):
27+
# self.val = x
28+
# self.left = None
29+
# self.right = None
30+
31+
class Solution:
32+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
33+
node = root
34+
35+
while node:
36+
37+
if p.val < node.val and q.val < node.val:
38+
node = node.left
39+
40+
elif p.val > node.val and q.val > node.val:
41+
node = node.right
42+
43+
else:
44+
return node

0 commit comments

Comments
ย (0)