알고리즘
[알고리즘] Deepest Leaves Sum
keel_im
2021. 4. 11. 19:41
반응형
포인트
- 트리 자료 구조에서 맨끝에 잎 부분을 더할 수 있는가? 물어보는 문제입니다. BFS 라고 표현할 수 도 있고 레벨 오더라고 표현할 수 있습니다.
🧶문서는 항상 수정될 수 있습니다. 비판은 환영합니다.
python
# Definition for a binary tree node.
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def deepestLeavesSum(self, root: TreeNode) -> int:
q, ans, qlen, current = deque([root]), 0, 0, 0
while q:
qlen, ans = len(q), 0
for _ in range(qlen):
current = q.popleft()
ans += current.val
if current.left:
q.append(current.left)
if current.right:
q.append(current.right)
return ans
반응형