Skip to content

Commit ceb9227

Browse files
committed
lowest-common-ancestor-of-a-binary-search-tree solution
1 parent 23fda39 commit ceb9227

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
class Solution:
9+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
10+
11+
# BST(이진 탐색 트리) 특성 활용해서 밸류값으로 LCA 찾기
12+
# 시간복잡도 O(log n)/ 최악O(n), 공간복잡도 O(1)
13+
while root:
14+
# p, q가 둘 다 root보다 작으면, LCA는 왼쪽 서브트리에 있음
15+
if p.val < root.val and q.val < root.val:
16+
root = root.left
17+
# p, q가 둘 다 root보다 크면, LCA는 오른쪽 서브트리에 있음
18+
elif p.val > root.val and q.val > root.val:
19+
root = root.right
20+
# p, q가 root의 양쪽에 나눠져 있는 경우 -> root가 LCA
21+
else:
22+
return root

0 commit comments

Comments
 (0)