반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- IT자격증
- 파이썬
- 토익 환급
- react
- 코드잇
- csts
- 소묘
- 연필소묘
- 취미
- 색연필
- 웹개발
- 코딩
- Python
- 다비드상
- 프로그래밍
- 미켈란젤로
- IT 자격증
- KSTQB
- 알고리즘
- 코딩테스트
- 테스팅 자격증
- 연필
- clean code
- 그림
- 클린 코드
- leetcode
- 프로그래머스
- 재택근무
- Kriss 재택
- PrivateRouter
Archives
- Today
- Total
글모음
[Leetcode] 938. Range Sum of BST [Python, easy] 본문
728x90
반응형



[ 문제 해설 ]
Tree를 탐방해서 low와 high 사이에 해당하는 값을 전부 더해서 반환하는 문제다.
[ 코드 1. Stack으로 구현 ]
class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
if not root: return 0
stack = [root]
ans = 0
while stack:
c_node = stack.pop()
if c_node:
if low<= c_node.val and c_node.val <= high:
ans += c_node.val
if c_node.left: stack.append(c_node.left)
if c_node.right: stack.append(c_node.right)
return ans
[ 코드 2. Recursion으로 구현 ]
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
if not root:return 0
return self.rangeSumBST(root.left, L, R) + \
self.rangeSumBST(root.right, L, R) + \
(root.val if L <= root.val <= R else 0)
backslash ' \ '는 가독성을 위해 쓰이는데, 긴 라인을 짧게 끊은 뒤, 연속해서 이어주는 역할을 한다.
value값 결정하는데 삼항연산을 사용했다.
< 역슬래쉬 없이 코드를 그냥 끊으면 오류가 난다. >
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
if not root:return 0
return self.rangeSumBST(root.left, L, R) +
self.rangeSumBST(root.right, L, R) +
(root.val if L <= root.val <= R else 0)
만약 그냥 역슬래쉬 없이 하면 오류남
What is the purpose of a backslash at the end of a line?
Just found the following module import in a Python code: from sqlalchemy.ext.declarative import declarative_base,\ AbstractConcreteBase I am curious about the backslash \ at the end of the ...
stackoverflow.com
삼항 연산자를 안쓰고 역슬래쉬도 안쓰면 코드가 이렇게 된다.
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
if not root :return 0
elif root.val < L : return self.rangeSumBST(root.right, L, R)
elif root.val > R : return self.rangeSumBST(root.left, L, R)
return root.val + self.rangeSumBST(root.right, L, R) + self.rangeSumBST(root.left, L, R)
1년전에 풀었던 문제인데 어떤식으로 풀었는지 기억이 안난다.. ㅋㅋㅋ
전에 역슬래쉬 써서 풀었는데 이제 와서 보니 역슬래쉬 용도도 순간 까먹었었다.
진짜 복습 여러번 해야겠다.

728x90
반응형