트리에서 BFS를 수행하면, 한 사이클을 돌 때마다 한 레벨의 노드를 전부 방문할 수 있다. 즉 O(N) 시간복잡도 내에 추가적인 알고리즘 없이 레벨순으로 모든 노드를 방문할 수 있다. 따라서 레벨합을 매우 쉽게 구할 수 있고, 이 레벨합 중 K번째 레벨합을 구하면 된다(이는 보통 O(NlogN) 시간복잡도가 걸릴 것이다)
풀이 코드
# 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 = rightclassSolution:
defkthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
nums = []
curr = [root]
while curr :
res = 0
tmp = []
for c in curr :
res += c.val
if c.left isnotNone :
tmp.append(c.left)
if c.right isnotNone :
tmp.append(c.right)
heappush(nums, -res)
curr = tmp
iflen(nums) < k :
return -1for _ inrange(k-1) :
heappop(nums)
return -heappop(nums)