from typing import Optional
# Definition for a binary tree node.
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: Optional[TreeNode]) -> int:
q0 = [root]
while True:
q = []
for qi in q0:
if qi.left:
if qi.left.val:
q.append(qi.left)
if qi.right:
if qi.right.val:
q.append(qi.right)
if not q:
break
q0 = q.copy()
a = sum([i.val for i in q0 if i.val])
return a
from collections import deque
class nt:
def __init__(self, root0):
self.n = len(root0)
rs = []
i0 = 0
for i in range(self.n):
if root0[i]:
i0 += 1
rs.append(TreeNode(root0[i]))
self.n0 = i0
i0 = 1
for i in range(self.n):
if rs[i].val:
rs[i].left = rs[i0]
rs[i].right = rs[i0+1]
i0 += 2
if i0 == self.n:
break
self.n1 = i0
self.r = rs[0]
def pr(self):
print(f'n: {self.n}, n0: {self.n0}')
q = deque()
q.append(self.r)
cnt = 0
while q:
q0 = q.copy()
q.clear()
for qi in q0:
s = f'level = {cnt:4}; p: '
s += f'{qi.val:4}; ' if qi.val is not None else "None"
if qi.left:
q.append(qi.left)
s += f'l: {qi.left.val:4}; ' if qi.left.val is not None else 'l: None; '
if qi.right:
q.append(qi.right)
s += f'l: {qi.right.val:4}; ' if qi.right.val is not None else 'l: None'
print(s)
cnt += 1
for i in range(2):
null = None
print(f'test case: {i}')
if i == 0:
root0 = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output = 15
if i == 1:
root0 = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output = 19
nt_i = nt(root0)
# nt_i.pr()
sol = Solution()
a = sol.deepestLeavesSum(nt_i.r)
print(a)
print(Output)
예: level = 2; parent 값 = 4; left 값 = 7; right 값 = None;
level = 2; p = 4; l = 7; l = None;