카테고리 없음
[Leetcode] 938. Range Sum of BST [Python, easy]
Nova_61
2021. 6. 12. 17:24
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
반응형