트리에서 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 = right
class Solution:
def kthLargestLevelSum(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 is not None :
tmp.append(c.left)
if c.right is not None :
tmp.append(c.right)
heappush(nums, -res)
curr = tmp
if len(nums) < k :
return -1
for _ in range(k-1) :
heappop(nums)
return -heappop(nums)