일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 스탭퍼
- FIT XR
- 월간
- 3줄정리
- 뭐든
- 사이드
- 미드시청
- leetcode
- 개발자
- Daily Challenge
- 화상영어
- 쓰릴오브파이트
- 10분
- 파비최
- 영어공부
- 매일
- 프로젝트
- realclass
- English
- 리얼 클래스
- 영어원서읽기
- 괜찮음
- 읽기
- 운동
- 링피트
- 30분
- 만화도
- 잡생각
- Problem Solving
- Writing
Archives
- Today
- Total
파비의 매일매일 공부기록
Today's Challenge 본문
https://leetcode.com/problems/binary-search-tree-iterator/
Binary Search Tree Iterator - 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
inorder 순회하는 class를 만드는 걸로 보인다.
python으로 작성한 다른 사람의 코드를 보니 Generator를 사용해서 풀었는데,
실무에서는 Generator를 거의 사용 안 해서 처음엔 이게 뭔가.. 했다.
yield 키워드를 사용하게 되는데
이걸 호출하면 암시적으로 return이 호출되고, 그다음 호출하면 다음의 yield 코드가 실행되는 개념이다.
결국 _inorder내에서 _inorder를 재호출하게 되니까 중위순위 동작을 하게 된다.
소스는 다음과 같다.
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.iter = self._inorder(root)
self.n = next(self.iter, None)
def _inorder(self, node: Optional[TreeNode]) -> Generator[int, None, None]:
if node:
yield from self._inorder(node.left)
yield node.val
yield from self._inorder(node.right)
def next(self) -> int:
res, self.n = self.n, next(self.iter, None)
return res
def hasNext(self) -> bool:
return self.n is not None
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
Today's Challenge (0) | 2022.04.23 |
---|---|
Today's Challenge (0) | 2022.04.22 |
Today's Challenge (0) | 2022.04.21 |
Today's Challenge (0) | 2022.04.19 |
Today's Challenge (0) | 2022.04.18 |
Comments