[Leetcode 235] Lowest Common Ancestor of a Binary Search Tree

이재윤·2024년 12월 23일

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/

1) 코드

# 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':
        if p.val < root.val and q.val < root.val:
            return self.lowestCommonAncestor(root.left, p, q) 

        if p.val > root.val and q.val > root.val:
            return self.lowestCommonAncestor(root.right, p, q) 

        return root 

2) 해설

  • BST의 개념을 잘 활용하여야 하는 문제이다.
  • BST의 경우, 왼쪽 서브트리에는 현재 노드보다 작은 값이, 오른쪽 서브트리에는 현재 노드보다 큰 값이 있다
  • 만약에, P,Q가 모두 현재 노드보다 값이 작다면, 가장 낮은 공통 조상도 왼쪽 서브 트리에 있으므로, 왼쪽 서브트리로 진입한다.
  • 반대의 경우는, 오른쪽 서브트리로 진입한다.
  • 위의 두 가지가 모두 아닌 경우는, 바로 현재 노드가 P와 Q를 포함한 사이에 값이 있다는 의미이다.
    -> 따라서 이러한 경우는 BST의 정의에 따라 해당 노드가 가장 낮은 공통 조상이 되게 되고, 따라서 그 값을 리턴해주면 된다.

0개의 댓글