상위 150개 인터뷰쉬움

BST의 최하위 공통 조상

'BST의 최하위 공통 조상' 문제에 대한 자세한 가이드 및 Python 구현입니다.

문제 설명

쉬움

BST(이진 검색 트리)가 주어지면 BST에서 주어진 두 노드 중 가장 낮은 공통 조상(LCA) 노드를 찾습니다.

LCA의 정의에 따르면: "최하위 공통 조상은 두 노드 p와 q 사이에 p와 q를 모두 자손으로 갖는 T의 가장 낮은 노드로 정의됩니다(노드가 자체의 자손이 되도록 허용합니다)."

BST는 레벨 순서 목록으로 표시됩니다. LCA 노드의 값을 반환하는 lowestCommonAncestor(root: list, p: int, q: int) -> int 함수를 구현합니다.

제약
  • The number of nodes in the tree is in the range [2, 100000]
  • -1000000000 <= Node.val <= 1000000000
  • All Node.val are unique
  • p != q
  • p and q will exist in the BST

Example 1
Input
[6,2,8,0,4,7,9,None,None,3,5], 2, 8
Output
6
Explanation

The LCA of nodes 2 and 8 is 6, which is the root.

Example 2
Input
[6,2,8,0,4,7,9,None,None,3,5], 2, 4
Output
2
Explanation

The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself.

Example 3
Input
[2,1], 2, 1
Output
2
Explanation

The LCA of nodes 2 and 1 is 2.

Need a Hint?
세트나 힙과 같은 트리 관련 데이터 구조를 사용해 보세요.
Edge Cases to Watch
  • 빈 입력 구조
  • 단일 요소 입력
  • 큰 수치 범위

해결할 준비가 되셨나요?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

편집기에서 열기
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

권장 Python 리소스

관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.