일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 사이드
- Writing
- 만화도
- realclass
- 운동
- 30분
- leetcode
- 리얼 클래스
- 3줄정리
- 읽기
- 프로젝트
- 링피트
- 미드시청
- 화상영어
- 월간
- 스탭퍼
- Problem Solving
- English
- 영어원서읽기
- FIT XR
- Daily Challenge
- 뭐든
- 개발자
- 파비최
- 영어공부
- 잡생각
- 괜찮음
- 매일
- 쓰릴오브파이트
- 10분
Archives
- Today
- Total
파비의 매일매일 공부기록
Today's Challenge 본문
https://leetcode.com/problems/recover-binary-search-tree/
Recover Binary Search 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
음.. 이번 문제는 이해부터가 좀 어려운 듯?
그런데 매우 간단한 방법을 사용한 풀이가 있다. 재귀도 안쓰고.
공책에 Example에 대한 로직을 쭉 따라가봤는데 신기하게도 first와 second가 제대로 구해진다.
1. first는 root와 pre를 비교해서 딱 한 번만 구한다. BST 구조에 맞지 않는 값을 구하는 로직으로 보면 될 거 같다.
2. second는 first 값이 존재할 때, root와 pre를 비교해서 구한다. 이 작업은 여러 번 이루어질 수 있다.
작성한 소스는 다음과 같다.
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
s = []
pre, first, second = None, None, None
while root or len(s) > 0:
while root is not None:
s.append(root)
root = root.left
if len(s) > 0:
root = s.pop()
if first is None and pre and pre.val > root.val:
first = pre
if first and pre.val > root.val:
second = root
pre = root
root = root.right
first.val, second.val = second.val, first.val
반응형
'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.20 |
Today's Challenge (0) | 2022.04.18 |
Comments