235. Lowest Common Ancestor of a Binary Search Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# 바이너리 서치 트리 BST 에서 가장 가까운 조상 찾기
# BST 이므로, 왼쪽에 있으면 무조건 작은값, 오른쪽에 있으면 큰값
if not root:
return None
if root == p or root == q: # 둘중 하나가 root 와 같으면, 다른 하나는, 자식일테니, root 가 공통 조상
return root
if root.val > p.val and root.val > q.val: # 둘다 root 보다 작으면
# 왼쪽으로 내려가서 찾아야.
return self.lowestCommonAncestor(root.left, p, q)
elif root.val < p.val and root.val < q.val: # 둘다 root 보다 크면
# 오른쪽으로 내려가서 찾아야.
return self.lowestCommonAncestor(root.right, p, q)
else: # p 와 q가 양쪽에 하나씩 있는 경우
# root 가 공통 조상
return root'LeetCode > Grind169' 카테고리의 다른 글
| 141. Linked List Cycle ☆★★ (0) | 2025.04.22 |
|---|---|
| 110. Balanced Binary Tree ☆ (0) | 2025.04.22 |
| 733. Flood Fill (1) | 2025.04.22 |
| 704. Binary Search (0) | 2025.04.22 |
| 242. Valid Anagram (0) | 2025.04.22 |