Skip to content

Commit 9faf96b

Browse files
committed
FEAT: solve lowest-common-ancestor-of-a-binary-search-tree
1 parent d3dfa3c commit 9faf96b

File tree

1 file changed

+22
-0
lines changed
  • lowest-common-ancestor-of-a-binary-search-tree

1 file changed

+22
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
'''
2+
TC: O(h) (hλŠ” 트리의 높이)
3+
SC: O(1)
4+
풀이 방법: 이진 탐색 트리의 μ„±μ§ˆμ„ μ΄μš©ν•΄μ„œ
5+
p,q의 값이 ν˜„μž¬ λ…Έλ“œ 사이에 μžˆκ±°λ‚˜ p,q의 κ°’ 쀑 ν•˜λ‚˜λΌλ„ ν˜„μž¬ λ…Έλ“œμ™€ 같을 λ•ŒκΉŒμ§€ νƒμƒ‰ν•œλ‹€
6+
'''
7+
# Definition for a binary tree node.
8+
# class TreeNode:
9+
# def __init__(self, x):
10+
# self.val = x
11+
# self.left = None
12+
# self.right = None
13+
14+
class Solution:
15+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
16+
while root:
17+
if p.val < root.val and q.val < root.val:
18+
root = root.left
19+
elif p.val > root.val and q.val > root.val:
20+
root = root.right
21+
else:
22+
return root

0 commit comments

Comments
Β (0)