일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 뭐든
- leetcode
- 미드시청
- 쓰릴오브파이트
- 괜찮음
- 프로젝트
- 잡생각
- 개발자
- 읽기
- 스탭퍼
- Daily Challenge
- 월간
- FIT XR
- 운동
- 영어공부
- 사이드
- 링피트
- 화상영어
- 3줄정리
- 리얼 클래스
- Problem Solving
- 영어원서읽기
- 파비최
- 30분
- 10분
- realclass
- 만화도
- English
- 매일
- Writing
Archives
- Today
- Total
파비의 매일매일 공부기록
Today's Challenge 본문
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
Lowest Common Ancestor of a Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
오랫만에 트리 구조의 문제
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
stack = [root]
parent = {root: None}
while p not in parent or q not in parent:
node = stack.pop()
if node.left:
parent[node.left] = node
stack.append(node.left)
if node.right:
parent[node.right] = node
stack.append(node.right)
ancestors = set()
while p:
ancestors.add(p)
p = parent[p]
while q not in ancestors:
q = parent[q]
return q
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
Today's Challenge (0) | 2022.07.28 |
---|---|
Today's Challenge (0) | 2022.07.27 |
Today's Challenge (0) | 2022.07.25 |
Today's Challenge (0) | 2022.07.24 |
Today's Challenge (0) | 2022.07.23 |
Comments